]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/execute.c
integritysetup: Check args to prevent assert
[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
33331d11
VB
4139 if (context->utmp_id) {
4140 const char *line = context->tty_path ?
4141 (path_startswith(context->tty_path, "/dev/") ?: context->tty_path) :
4142 NULL;
df0ff127 4143 utmp_put_init_process(context->utmp_id, getpid_cached(), getsid(0),
33331d11 4144 line,
023a4f67
LP
4145 context->utmp_mode == EXEC_UTMP_INIT ? INIT_PROCESS :
4146 context->utmp_mode == EXEC_UTMP_LOGIN ? LOGIN_PROCESS :
4147 USER_PROCESS,
6a93917d 4148 username);
33331d11 4149 }
d35fbf6b 4150
08f67696 4151 if (uid_is_valid(uid)) {
ff0af2a1
LP
4152 r = chown_terminal(STDIN_FILENO, uid);
4153 if (r < 0) {
4154 *exit_status = EXIT_STDIN;
12145637 4155 return log_unit_error_errno(unit, r, "Failed to change ownership of terminal: %m");
071830ff 4156 }
d35fbf6b 4157 }
8e274523 4158
4e1dfa45 4159 /* If delegation is enabled we'll pass ownership of the cgroup to the user of the new process. On cgroup v1
62b9bb26 4160 * this is only about systemd's own hierarchy, i.e. not the controller hierarchies, simply because that's not
4e1dfa45 4161 * safe. On cgroup v2 there's only one hierarchy anyway, and delegation is safe there, hence in that case only
62b9bb26 4162 * touch a single hierarchy too. */
584b8688 4163 if (params->cgroup_path && context->user && (params->flags & EXEC_CGROUP_DELEGATE)) {
62b9bb26 4164 r = cg_set_access(SYSTEMD_CGROUP_CONTROLLER, params->cgroup_path, uid, gid);
ff0af2a1
LP
4165 if (r < 0) {
4166 *exit_status = EXIT_CGROUP;
12145637 4167 return log_unit_error_errno(unit, r, "Failed to adjust control group access: %m");
034c6ed7 4168 }
d35fbf6b 4169 }
034c6ed7 4170
5b10116e 4171 for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
8679efde 4172 r = setup_exec_directory(context, params, uid, gid, dt, exit_status);
12145637
LP
4173 if (r < 0)
4174 return log_unit_error_errno(unit, r, "Failed to set up special execution directory in %s: %m", params->prefix[dt]);
d35fbf6b 4175 }
94f04347 4176
bb0c0d6f
LP
4177 if (FLAGS_SET(params->flags, EXEC_WRITE_CREDENTIALS)) {
4178 r = setup_credentials(context, params, unit->id, uid);
4179 if (r < 0) {
4180 *exit_status = EXIT_CREDENTIALS;
4181 return log_unit_error_errno(unit, r, "Failed to set up credentials: %m");
4182 }
4183 }
4184
7bce046b 4185 r = build_environment(
fd63e712 4186 unit,
7bce046b
LP
4187 context,
4188 params,
4189 n_fds,
4190 home,
4191 username,
4192 shell,
4193 journal_stream_dev,
4194 journal_stream_ino,
4195 &our_env);
2065ca69
JW
4196 if (r < 0) {
4197 *exit_status = EXIT_MEMORY;
12145637 4198 return log_oom();
2065ca69
JW
4199 }
4200
4201 r = build_pass_environment(context, &pass_env);
4202 if (r < 0) {
4203 *exit_status = EXIT_MEMORY;
12145637 4204 return log_oom();
2065ca69
JW
4205 }
4206
8c35c10d 4207 /* The PATH variable is set to the default path in params->environment.
4208 * However, this is overridden if user specified fields have PATH set.
4209 * The intention is to also override PATH if the user does
4210 * not specify PATH and the user has specified ExecSearchPath
4211 */
4212
4213 if (!strv_isempty(context->exec_search_path)) {
4214 _cleanup_free_ char *joined = NULL;
4215
4216 joined = strv_join(context->exec_search_path, ":");
4217 if (!joined) {
4218 *exit_status = EXIT_MEMORY;
4219 return log_oom();
4220 }
4221
4222 r = strv_env_assign(&joined_exec_search_path, "PATH", joined);
4223 if (r < 0) {
4224 *exit_status = EXIT_MEMORY;
4225 return log_oom();
4226 }
4227 }
4228
4ab3d29f 4229 accum_env = strv_env_merge(params->environment,
2065ca69 4230 our_env,
8c35c10d 4231 joined_exec_search_path,
2065ca69
JW
4232 pass_env,
4233 context->environment,
44e5d006 4234 files_env);
2065ca69
JW
4235 if (!accum_env) {
4236 *exit_status = EXIT_MEMORY;
12145637 4237 return log_oom();
2065ca69 4238 }
1280503b 4239 accum_env = strv_env_clean(accum_env);
2065ca69 4240
096424d1 4241 (void) umask(context->umask);
b213e1c1 4242
b1edf445 4243 r = setup_keyring(unit, context, params, uid, gid);
74dd6b51
LP
4244 if (r < 0) {
4245 *exit_status = EXIT_KEYRING;
12145637 4246 return log_unit_error_errno(unit, r, "Failed to set up kernel keyring: %m");
74dd6b51
LP
4247 }
4248
165a31c0 4249 /* We need sandboxing if the caller asked us to apply it and the command isn't explicitly excepted from it */
1703fa41 4250 needs_sandboxing = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & EXEC_COMMAND_FULLY_PRIVILEGED);
7f18ef0a 4251
165a31c0
LP
4252 /* 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 */
4253 needs_ambient_hack = (params->flags & EXEC_APPLY_SANDBOXING) && (command->flags & EXEC_COMMAND_AMBIENT_MAGIC) && !ambient_capabilities_supported();
7f18ef0a 4254
165a31c0
LP
4255 /* 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 */
4256 if (needs_ambient_hack)
4257 needs_setuid = false;
4258 else
4259 needs_setuid = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & (EXEC_COMMAND_FULLY_PRIVILEGED|EXEC_COMMAND_NO_SETUID));
4260
4261 if (needs_sandboxing) {
7f18ef0a
FK
4262 /* MAC enablement checks need to be done before a new mount ns is created, as they rely on /sys being
4263 * present. The actual MAC context application will happen later, as late as possible, to avoid
4264 * impacting our own code paths. */
4265
349cc4a5 4266#if HAVE_SELINUX
43b1f709 4267 use_selinux = mac_selinux_use();
7f18ef0a 4268#endif
f9fa32f0 4269#if ENABLE_SMACK
43b1f709 4270 use_smack = mac_smack_use();
7f18ef0a 4271#endif
349cc4a5 4272#if HAVE_APPARMOR
43b1f709 4273 use_apparmor = mac_apparmor_use();
7f18ef0a 4274#endif
165a31c0 4275 }
7f18ef0a 4276
ce932d2d
LP
4277 if (needs_sandboxing) {
4278 int which_failed;
4279
4280 /* Let's set the resource limits before we call into PAM, so that pam_limits wins over what
4281 * is set here. (See below.) */
4282
4283 r = setrlimit_closest_all((const struct rlimit* const *) context->rlimit, &which_failed);
4284 if (r < 0) {
4285 *exit_status = EXIT_LIMITS;
4286 return log_unit_error_errno(unit, r, "Failed to adjust resource limit RLIMIT_%s: %m", rlimit_to_string(which_failed));
4287 }
4288 }
4289
0af07108 4290 if (needs_setuid && context->pam_name && username) {
ce932d2d
LP
4291 /* Let's call into PAM after we set up our own idea of resource limits to that pam_limits
4292 * wins here. (See above.) */
4293
1da37e58 4294 /* All fds passed in the fds array will be closed in the pam child process. */
0af07108
ZJS
4295 r = setup_pam(context->pam_name, username, uid, gid, context->tty_path, &accum_env, fds, n_fds);
4296 if (r < 0) {
4297 *exit_status = EXIT_PAM;
4298 return log_unit_error_errno(unit, r, "Failed to set up PAM session: %m");
165a31c0 4299 }
ac45f971 4300
0af07108
ZJS
4301 ngids_after_pam = getgroups_alloc(&gids_after_pam);
4302 if (ngids_after_pam < 0) {
4303 *exit_status = EXIT_MEMORY;
4304 return log_unit_error_errno(unit, ngids_after_pam, "Failed to obtain groups after setting up PAM: %m");
5749f855 4305 }
b213e1c1 4306 }
5749f855 4307
0af07108 4308 if (needs_sandboxing && context->private_users && !have_effective_cap(CAP_SYS_ADMIN)) {
5749f855
AZ
4309 /* If we're unprivileged, set up the user namespace first to enable use of the other namespaces.
4310 * Users with CAP_SYS_ADMIN can set up user namespaces last because they will be able to
4311 * set up the all of the other namespaces (i.e. network, mount, UTS) without a user namespace. */
0af07108
ZJS
4312
4313 userns_set_up = true;
4314 r = setup_private_users(saved_uid, saved_gid, uid, gid);
4315 if (r < 0) {
4316 *exit_status = EXIT_USER;
4317 return log_unit_error_errno(unit, r, "Failed to set up user namespacing for unprivileged user: %m");
5749f855
AZ
4318 }
4319 }
4320
a8d08f39
LP
4321 if ((context->private_network || context->network_namespace_path) && runtime && runtime->netns_storage_socket[0] >= 0) {
4322
6e2d7c4f 4323 if (ns_type_supported(NAMESPACE_NET)) {
54c2459d 4324 r = setup_shareable_ns(runtime->netns_storage_socket, CLONE_NEWNET);
ee00d1e9
ZJS
4325 if (r == -EPERM)
4326 log_unit_warning_errno(unit, r,
4327 "PrivateNetwork=yes is configured, but network namespace setup failed, ignoring: %m");
4328 else if (r < 0) {
6e2d7c4f
MS
4329 *exit_status = EXIT_NETWORK;
4330 return log_unit_error_errno(unit, r, "Failed to set up network namespacing: %m");
4331 }
a8d08f39
LP
4332 } else if (context->network_namespace_path) {
4333 *exit_status = EXIT_NETWORK;
ee00d1e9
ZJS
4334 return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EOPNOTSUPP),
4335 "NetworkNamespacePath= is not supported, refusing.");
6e2d7c4f
MS
4336 } else
4337 log_unit_warning(unit, "PrivateNetwork=yes is configured, but the kernel does not support network namespaces, ignoring.");
d35fbf6b 4338 }
169c1bda 4339
a70581ff
XR
4340 if ((context->private_ipc || context->ipc_namespace_path) && runtime && runtime->ipcns_storage_socket[0] >= 0) {
4341
4342 if (ns_type_supported(NAMESPACE_IPC)) {
4343 r = setup_shareable_ns(runtime->ipcns_storage_socket, CLONE_NEWIPC);
4344 if (r == -EPERM)
4345 log_unit_warning_errno(unit, r,
4346 "PrivateIPC=yes is configured, but IPC namespace setup failed, ignoring: %m");
4347 else if (r < 0) {
4348 *exit_status = EXIT_NAMESPACE;
4349 return log_unit_error_errno(unit, r, "Failed to set up IPC namespacing: %m");
4350 }
4351 } else if (context->ipc_namespace_path) {
4352 *exit_status = EXIT_NAMESPACE;
4353 return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EOPNOTSUPP),
4354 "IPCNamespacePath= is not supported, refusing.");
4355 } else
4356 log_unit_warning(unit, "PrivateIPC=yes is configured, but the kernel does not support IPC namespaces, ignoring.");
4357 }
4358
ee818b89 4359 needs_mount_namespace = exec_needs_mount_namespace(context, params, runtime);
ee818b89 4360 if (needs_mount_namespace) {
7cc5ef5f
ZJS
4361 _cleanup_free_ char *error_path = NULL;
4362
9f71ba8d 4363 r = apply_mount_namespace(unit, command->flags, context, params, runtime, &error_path);
3fbe8dbe
LP
4364 if (r < 0) {
4365 *exit_status = EXIT_NAMESPACE;
7cc5ef5f
ZJS
4366 return log_unit_error_errno(unit, r, "Failed to set up mount namespacing%s%s: %m",
4367 error_path ? ": " : "", strempty(error_path));
3fbe8dbe 4368 }
d35fbf6b 4369 }
81a2b7ce 4370
daf8f72b
LP
4371 if (needs_sandboxing) {
4372 r = apply_protect_hostname(unit, context, exit_status);
4373 if (r < 0)
4374 return r;
aecd5ac6
TM
4375 }
4376
5749f855
AZ
4377 /* Drop groups as early as possible.
4378 * This needs to be done after PrivateDevices=y setup as device nodes should be owned by the host's root.
4379 * For non-root in a userns, devices will be owned by the user/group before the group change, and nobody. */
165a31c0 4380 if (needs_setuid) {
afb11bf1
DG
4381 _cleanup_free_ gid_t *gids_to_enforce = NULL;
4382 int ngids_to_enforce = 0;
4383
4384 ngids_to_enforce = merge_gid_lists(supplementary_gids,
4385 ngids,
4386 gids_after_pam,
4387 ngids_after_pam,
4388 &gids_to_enforce);
4389 if (ngids_to_enforce < 0) {
4390 *exit_status = EXIT_MEMORY;
4391 return log_unit_error_errno(unit,
4392 ngids_to_enforce,
4393 "Failed to merge group lists. Group membership might be incorrect: %m");
4394 }
4395
4396 r = enforce_groups(gid, gids_to_enforce, ngids_to_enforce);
096424d1
LP
4397 if (r < 0) {
4398 *exit_status = EXIT_GROUP;
12145637 4399 return log_unit_error_errno(unit, r, "Changing group credentials failed: %m");
096424d1 4400 }
165a31c0 4401 }
096424d1 4402
5749f855
AZ
4403 /* If the user namespace was not set up above, try to do it now.
4404 * It's preferred to set up the user namespace later (after all other namespaces) so as not to be
4405 * restricted by rules pertaining to combining user namspaces with other namespaces (e.g. in the
4406 * case of mount namespaces being less privileged when the mount point list is copied from a
4407 * different user namespace). */
9008e1ac 4408
5749f855
AZ
4409 if (needs_sandboxing && context->private_users && !userns_set_up) {
4410 r = setup_private_users(saved_uid, saved_gid, uid, gid);
4411 if (r < 0) {
4412 *exit_status = EXIT_USER;
4413 return log_unit_error_errno(unit, r, "Failed to set up user namespacing: %m");
d251207d
LP
4414 }
4415 }
4416
9f71ba8d
ZJS
4417 /* Now that the mount namespace has been set up and privileges adjusted, let's look for the thing we
4418 * shall execute. */
4419
4420 _cleanup_free_ char *executable = NULL;
b83d5050 4421 _cleanup_close_ int executable_fd = -1;
8c35c10d 4422 r = find_executable_full(command->path, /* root= */ NULL, context->exec_search_path, false, &executable, &executable_fd);
9f71ba8d
ZJS
4423 if (r < 0) {
4424 if (r != -ENOMEM && (command->flags & EXEC_COMMAND_IGNORE_FAILURE)) {
c2503e35
RH
4425 log_unit_struct_errno(unit, LOG_INFO, r,
4426 "MESSAGE_ID=" SD_MESSAGE_SPAWN_FAILED_STR,
4427 LOG_UNIT_INVOCATION_ID(unit),
4428 LOG_UNIT_MESSAGE(unit, "Executable %s missing, skipping: %m",
4429 command->path),
4430 "EXECUTABLE=%s", command->path);
9f71ba8d
ZJS
4431 return 0;
4432 }
4433
4434 *exit_status = EXIT_EXEC;
c2503e35
RH
4435
4436 return log_unit_struct_errno(unit, LOG_INFO, r,
4437 "MESSAGE_ID=" SD_MESSAGE_SPAWN_FAILED_STR,
4438 LOG_UNIT_INVOCATION_ID(unit),
4439 LOG_UNIT_MESSAGE(unit, "Failed to locate executable %s: %m",
4440 command->path),
4441 "EXECUTABLE=%s", command->path);
9f71ba8d
ZJS
4442 }
4443
b83d5050
ZJS
4444 r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, executable_fd, &executable_fd);
4445 if (r < 0) {
4446 *exit_status = EXIT_FDS;
4447 return log_unit_error_errno(unit, r, "Failed to shift fd and set FD_CLOEXEC: %m");
4448 }
4449
9f71ba8d 4450#if HAVE_SELINUX
49590d67
MS
4451 if (needs_sandboxing && use_selinux && params->selinux_context_net) {
4452 int fd = -1;
4453
4454 if (socket_fd >= 0)
4455 fd = socket_fd;
4456 else if (params->n_socket_fds == 1)
4457 /* If stdin is not connected to a socket but we are triggered by exactly one socket unit then we
4458 * use context from that fd to compute the label. */
4459 fd = params->fds[0];
4460
4461 if (fd >= 0) {
4462 r = mac_selinux_get_child_mls_label(fd, executable, context->selinux_context, &mac_selinux_context_net);
4463 if (r < 0) {
4464 *exit_status = EXIT_SELINUX_CONTEXT;
4465 return log_unit_error_errno(unit, r, "Failed to determine SELinux context: %m");
4466 }
9f71ba8d
ZJS
4467 }
4468 }
4469#endif
4470
165a31c0 4471 /* We repeat the fd closing here, to make sure that nothing is leaked from the PAM modules. Note that we are
a70581ff 4472 * 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
4473 * however if we have it as we want to keep it open until the final execve(). */
4474
1da37e58 4475 r = close_all_fds(keep_fds, n_keep_fds);
ff0af2a1
LP
4476 if (r >= 0)
4477 r = shift_fds(fds, n_fds);
4478 if (r >= 0)
25b583d7 4479 r = flags_fds(fds, n_socket_fds, n_storage_fds, context->non_blocking);
ff0af2a1
LP
4480 if (r < 0) {
4481 *exit_status = EXIT_FDS;
12145637 4482 return log_unit_error_errno(unit, r, "Failed to adjust passed file descriptors: %m");
d35fbf6b 4483 }
e66cf1a3 4484
5686391b
LP
4485 /* At this point, the fds we want to pass to the program are all ready and set up, with O_CLOEXEC turned off
4486 * and at the right fd numbers. The are no other fds open, with one exception: the exec_fd if it is defined,
4487 * and it has O_CLOEXEC set, after all we want it to be closed by the execve(), so that our parent knows we
4488 * came this far. */
4489
165a31c0 4490 secure_bits = context->secure_bits;
e66cf1a3 4491
165a31c0
LP
4492 if (needs_sandboxing) {
4493 uint64_t bset;
e66cf1a3 4494
ce932d2d
LP
4495 /* Set the RTPRIO resource limit to 0, but only if nothing else was explicitly
4496 * requested. (Note this is placed after the general resource limit initialization, see
4497 * above, in order to take precedence.) */
f4170c67
LP
4498 if (context->restrict_realtime && !context->rlimit[RLIMIT_RTPRIO]) {
4499 if (setrlimit(RLIMIT_RTPRIO, &RLIMIT_MAKE_CONST(0)) < 0) {
4500 *exit_status = EXIT_LIMITS;
12145637 4501 return log_unit_error_errno(unit, errno, "Failed to adjust RLIMIT_RTPRIO resource limit: %m");
f4170c67
LP
4502 }
4503 }
4504
37ac2744
JB
4505#if ENABLE_SMACK
4506 /* LSM Smack needs the capability CAP_MAC_ADMIN to change the current execution security context of the
4507 * process. This is the latest place before dropping capabilities. Other MAC context are set later. */
4508 if (use_smack) {
b83d5050 4509 r = setup_smack(context, executable_fd);
37ac2744
JB
4510 if (r < 0) {
4511 *exit_status = EXIT_SMACK_PROCESS_LABEL;
4512 return log_unit_error_errno(unit, r, "Failed to set SMACK process label: %m");
4513 }
4514 }
4515#endif
4516
165a31c0
LP
4517 bset = context->capability_bounding_set;
4518 /* If the ambient caps hack is enabled (which means the kernel can't do them, and the user asked for
4519 * our magic fallback), then let's add some extra caps, so that the service can drop privs of its own,
4520 * instead of us doing that */
4521 if (needs_ambient_hack)
4522 bset |= (UINT64_C(1) << CAP_SETPCAP) |
4523 (UINT64_C(1) << CAP_SETUID) |
4524 (UINT64_C(1) << CAP_SETGID);
4525
4526 if (!cap_test_all(bset)) {
4527 r = capability_bounding_set_drop(bset, false);
ff0af2a1
LP
4528 if (r < 0) {
4529 *exit_status = EXIT_CAPABILITIES;
12145637 4530 return log_unit_error_errno(unit, r, "Failed to drop capabilities: %m");
3b8bddde 4531 }
4c2630eb 4532 }
3b8bddde 4533
16fcb191
TK
4534 /* Ambient capabilities are cleared during setresuid() (in enforce_user()) even with
4535 * keep-caps set.
4536 * To be able to raise the ambient capabilities after setresuid() they have to be
4537 * added to the inherited set and keep caps has to be set (done in enforce_user()).
4538 * After setresuid() the ambient capabilities can be raised as they are present in
4539 * the permitted and inhertiable set. However it is possible that someone wants to
4540 * set ambient capabilities without changing the user, so we also set the ambient
4541 * capabilities here.
4542 * The requested ambient capabilities are raised in the inheritable set if the
4543 * second argument is true. */
943800f4 4544 if (!needs_ambient_hack) {
755d4b67
IP
4545 r = capability_ambient_set_apply(context->capability_ambient_set, true);
4546 if (r < 0) {
4547 *exit_status = EXIT_CAPABILITIES;
12145637 4548 return log_unit_error_errno(unit, r, "Failed to apply ambient capabilities (before UID change): %m");
755d4b67 4549 }
755d4b67 4550 }
165a31c0 4551 }
755d4b67 4552
fa97f630
JB
4553 /* chroot to root directory first, before we lose the ability to chroot */
4554 r = apply_root_directory(context, params, needs_mount_namespace, exit_status);
4555 if (r < 0)
4556 return log_unit_error_errno(unit, r, "Chrooting to the requested root directory failed: %m");
4557
165a31c0 4558 if (needs_setuid) {
08f67696 4559 if (uid_is_valid(uid)) {
ff0af2a1
LP
4560 r = enforce_user(context, uid);
4561 if (r < 0) {
4562 *exit_status = EXIT_USER;
12145637 4563 return log_unit_error_errno(unit, r, "Failed to change UID to " UID_FMT ": %m", uid);
5b6319dc 4564 }
165a31c0
LP
4565
4566 if (!needs_ambient_hack &&
4567 context->capability_ambient_set != 0) {
755d4b67 4568
16fcb191 4569 /* Raise the ambient capabilities after user change. */
755d4b67
IP
4570 r = capability_ambient_set_apply(context->capability_ambient_set, false);
4571 if (r < 0) {
4572 *exit_status = EXIT_CAPABILITIES;
12145637 4573 return log_unit_error_errno(unit, r, "Failed to apply ambient capabilities (after UID change): %m");
755d4b67 4574 }
755d4b67 4575 }
5b6319dc 4576 }
165a31c0 4577 }
d35fbf6b 4578
56ef8db9
JB
4579 /* Apply working directory here, because the working directory might be on NFS and only the user running
4580 * this service might have the correct privilege to change to the working directory */
fa97f630 4581 r = apply_working_directory(context, params, home, exit_status);
56ef8db9
JB
4582 if (r < 0)
4583 return log_unit_error_errno(unit, r, "Changing to the requested working directory failed: %m");
4584
165a31c0 4585 if (needs_sandboxing) {
37ac2744 4586 /* Apply other MAC contexts late, but before seccomp syscall filtering, as those should really be last to
5cd9cd35
LP
4587 * influence our own codepaths as little as possible. Moreover, applying MAC contexts usually requires
4588 * syscalls that are subject to seccomp filtering, hence should probably be applied before the syscalls
4589 * are restricted. */
4590
349cc4a5 4591#if HAVE_SELINUX
43b1f709 4592 if (use_selinux) {
5cd9cd35
LP
4593 char *exec_context = mac_selinux_context_net ?: context->selinux_context;
4594
4595 if (exec_context) {
4596 r = setexeccon(exec_context);
4597 if (r < 0) {
4598 *exit_status = EXIT_SELINUX_CONTEXT;
12145637 4599 return log_unit_error_errno(unit, r, "Failed to change SELinux context to %s: %m", exec_context);
5cd9cd35
LP
4600 }
4601 }
4602 }
4603#endif
4604
349cc4a5 4605#if HAVE_APPARMOR
43b1f709 4606 if (use_apparmor && context->apparmor_profile) {
5cd9cd35
LP
4607 r = aa_change_onexec(context->apparmor_profile);
4608 if (r < 0 && !context->apparmor_profile_ignore) {
4609 *exit_status = EXIT_APPARMOR_PROFILE;
12145637 4610 return log_unit_error_errno(unit, errno, "Failed to prepare AppArmor profile change to %s: %m", context->apparmor_profile);
5cd9cd35
LP
4611 }
4612 }
4613#endif
4614
165a31c0 4615 /* PR_GET_SECUREBITS is not privileged, while PR_SET_SECUREBITS is. So to suppress potential EPERMs
dbdc4098
TK
4616 * we'll try not to call PR_SET_SECUREBITS unless necessary. Setting securebits requires
4617 * CAP_SETPCAP. */
4618 if (prctl(PR_GET_SECUREBITS) != secure_bits) {
69e3234d 4619 /* CAP_SETPCAP is required to set securebits. This capability is raised into the
dbdc4098
TK
4620 * effective set here.
4621 * The effective set is overwritten during execve with the following values:
4622 * - ambient set (for non-root processes)
4623 * - (inheritable | bounding) set for root processes)
4624 *
4625 * Hence there is no security impact to raise it in the effective set before execve
4626 */
4627 r = capability_gain_cap_setpcap(NULL);
4628 if (r < 0) {
4629 *exit_status = EXIT_CAPABILITIES;
4630 return log_unit_error_errno(unit, r, "Failed to gain CAP_SETPCAP for setting secure bits");
4631 }
755d4b67 4632 if (prctl(PR_SET_SECUREBITS, secure_bits) < 0) {
ff0af2a1 4633 *exit_status = EXIT_SECUREBITS;
12145637 4634 return log_unit_error_errno(unit, errno, "Failed to set process secure bits: %m");
ff01d048 4635 }
dbdc4098 4636 }
5b6319dc 4637
59eeb84b 4638 if (context_has_no_new_privileges(context))
d35fbf6b 4639 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
ff0af2a1 4640 *exit_status = EXIT_NO_NEW_PRIVILEGES;
12145637 4641 return log_unit_error_errno(unit, errno, "Failed to disable new privileges: %m");
d35fbf6b
DM
4642 }
4643
349cc4a5 4644#if HAVE_SECCOMP
469830d1
LP
4645 r = apply_address_families(unit, context);
4646 if (r < 0) {
4647 *exit_status = EXIT_ADDRESS_FAMILIES;
12145637 4648 return log_unit_error_errno(unit, r, "Failed to restrict address families: %m");
4c2630eb 4649 }
04aa0cb9 4650
469830d1
LP
4651 r = apply_memory_deny_write_execute(unit, context);
4652 if (r < 0) {
4653 *exit_status = EXIT_SECCOMP;
12145637 4654 return log_unit_error_errno(unit, r, "Failed to disable writing to executable memory: %m");
f3e43635 4655 }
f4170c67 4656
469830d1
LP
4657 r = apply_restrict_realtime(unit, context);
4658 if (r < 0) {
4659 *exit_status = EXIT_SECCOMP;
12145637 4660 return log_unit_error_errno(unit, r, "Failed to apply realtime restrictions: %m");
f4170c67
LP
4661 }
4662
f69567cb
LP
4663 r = apply_restrict_suid_sgid(unit, context);
4664 if (r < 0) {
4665 *exit_status = EXIT_SECCOMP;
4666 return log_unit_error_errno(unit, r, "Failed to apply SUID/SGID restrictions: %m");
4667 }
4668
add00535
LP
4669 r = apply_restrict_namespaces(unit, context);
4670 if (r < 0) {
4671 *exit_status = EXIT_SECCOMP;
12145637 4672 return log_unit_error_errno(unit, r, "Failed to apply namespace restrictions: %m");
add00535
LP
4673 }
4674
469830d1
LP
4675 r = apply_protect_sysctl(unit, context);
4676 if (r < 0) {
4677 *exit_status = EXIT_SECCOMP;
12145637 4678 return log_unit_error_errno(unit, r, "Failed to apply sysctl restrictions: %m");
502d704e
DH
4679 }
4680
469830d1
LP
4681 r = apply_protect_kernel_modules(unit, context);
4682 if (r < 0) {
4683 *exit_status = EXIT_SECCOMP;
12145637 4684 return log_unit_error_errno(unit, r, "Failed to apply module loading restrictions: %m");
59eeb84b
LP
4685 }
4686
84703040
KK
4687 r = apply_protect_kernel_logs(unit, context);
4688 if (r < 0) {
4689 *exit_status = EXIT_SECCOMP;
4690 return log_unit_error_errno(unit, r, "Failed to apply kernel log restrictions: %m");
4691 }
4692
fc64760d
KK
4693 r = apply_protect_clock(unit, context);
4694 if (r < 0) {
4695 *exit_status = EXIT_SECCOMP;
4696 return log_unit_error_errno(unit, r, "Failed to apply clock restrictions: %m");
4697 }
4698
469830d1
LP
4699 r = apply_private_devices(unit, context);
4700 if (r < 0) {
4701 *exit_status = EXIT_SECCOMP;
12145637 4702 return log_unit_error_errno(unit, r, "Failed to set up private devices: %m");
469830d1
LP
4703 }
4704
4705 r = apply_syscall_archs(unit, context);
4706 if (r < 0) {
4707 *exit_status = EXIT_SECCOMP;
12145637 4708 return log_unit_error_errno(unit, r, "Failed to apply syscall architecture restrictions: %m");
ba128bb8
LP
4709 }
4710
78e864e5
TM
4711 r = apply_lock_personality(unit, context);
4712 if (r < 0) {
4713 *exit_status = EXIT_SECCOMP;
12145637 4714 return log_unit_error_errno(unit, r, "Failed to lock personalities: %m");
78e864e5
TM
4715 }
4716
9df2cdd8
TM
4717 r = apply_syscall_log(unit, context);
4718 if (r < 0) {
4719 *exit_status = EXIT_SECCOMP;
4720 return log_unit_error_errno(unit, r, "Failed to apply system call log filters: %m");
4721 }
4722
5cd9cd35
LP
4723 /* This really should remain the last step before the execve(), to make sure our own code is unaffected
4724 * by the filter as little as possible. */
165a31c0 4725 r = apply_syscall_filter(unit, context, needs_ambient_hack);
469830d1
LP
4726 if (r < 0) {
4727 *exit_status = EXIT_SECCOMP;
12145637 4728 return log_unit_error_errno(unit, r, "Failed to apply system call filters: %m");
d35fbf6b
DM
4729 }
4730#endif
b1994387
ILG
4731
4732#if HAVE_LIBBPF
4733 r = apply_restrict_filesystems(unit, context);
4734 if (r < 0) {
4735 *exit_status = EXIT_BPF;
4736 return log_unit_error_errno(unit, r, "Failed to restrict filesystems: %m");
4737 }
4738#endif
4739
d35fbf6b 4740 }
034c6ed7 4741
00819cc1
LP
4742 if (!strv_isempty(context->unset_environment)) {
4743 char **ee = NULL;
4744
4745 ee = strv_env_delete(accum_env, 1, context->unset_environment);
4746 if (!ee) {
4747 *exit_status = EXIT_MEMORY;
12145637 4748 return log_oom();
00819cc1
LP
4749 }
4750
130d3d22 4751 strv_free_and_replace(accum_env, ee);
00819cc1
LP
4752 }
4753
7ca69792
AZ
4754 if (!FLAGS_SET(command->flags, EXEC_COMMAND_NO_ENV_EXPAND)) {
4755 replaced_argv = replace_env_argv(command->argv, accum_env);
4756 if (!replaced_argv) {
4757 *exit_status = EXIT_MEMORY;
4758 return log_oom();
4759 }
4760 final_argv = replaced_argv;
4761 } else
4762 final_argv = command->argv;
034c6ed7 4763
f1d34068 4764 if (DEBUG_LOGGING) {
c2b2df60 4765 _cleanup_free_ char *line = NULL;
81a2b7ce 4766
8a62620e
ZJS
4767 line = quote_command_line(final_argv);
4768 if (!line) {
4769 *exit_status = EXIT_MEMORY;
4770 return log_oom();
4771 }
4772
4773 log_unit_struct(unit, LOG_DEBUG,
4774 "EXECUTABLE=%s", executable,
4775 LOG_UNIT_MESSAGE(unit, "Executing: %s", line));
d35fbf6b 4776 }
dd305ec9 4777
5686391b
LP
4778 if (exec_fd >= 0) {
4779 uint8_t hot = 1;
4780
4781 /* We have finished with all our initializations. Let's now let the manager know that. From this point
4782 * on, if the manager sees POLLHUP on the exec_fd, then execve() was successful. */
4783
4784 if (write(exec_fd, &hot, sizeof(hot)) < 0) {
4785 *exit_status = EXIT_EXEC;
4786 return log_unit_error_errno(unit, errno, "Failed to enable exec_fd: %m");
4787 }
4788 }
4789
a6d9111c 4790 r = fexecve_or_execve(executable_fd, executable, final_argv, accum_env);
5686391b
LP
4791
4792 if (exec_fd >= 0) {
4793 uint8_t hot = 0;
4794
4795 /* The execve() failed. This means the exec_fd is still open. Which means we need to tell the manager
4796 * that POLLHUP on it no longer means execve() succeeded. */
4797
4798 if (write(exec_fd, &hot, sizeof(hot)) < 0) {
4799 *exit_status = EXIT_EXEC;
4800 return log_unit_error_errno(unit, errno, "Failed to disable exec_fd: %m");
4801 }
4802 }
12145637 4803
ff0af2a1 4804 *exit_status = EXIT_EXEC;
9f71ba8d 4805 return log_unit_error_errno(unit, r, "Failed to execute %s: %m", executable);
d35fbf6b 4806}
81a2b7ce 4807
34cf6c43 4808static int exec_context_load_environment(const Unit *unit, const ExecContext *c, char ***l);
2caa38e9 4809static int exec_context_named_iofds(const ExecContext *c, const ExecParameters *p, int named_iofds[static 3]);
34cf6c43 4810
f2341e0a
LP
4811int exec_spawn(Unit *unit,
4812 ExecCommand *command,
d35fbf6b
DM
4813 const ExecContext *context,
4814 const ExecParameters *params,
4815 ExecRuntime *runtime,
29206d46 4816 DynamicCreds *dcreds,
d35fbf6b 4817 pid_t *ret) {
8351ceae 4818
ee39ca20 4819 int socket_fd, r, named_iofds[3] = { -1, -1, -1 }, *fds = NULL;
78f93209 4820 _cleanup_free_ char *subcgroup_path = NULL;
d35fbf6b 4821 _cleanup_strv_free_ char **files_env = NULL;
da6053d0 4822 size_t n_storage_fds = 0, n_socket_fds = 0;
ff0af2a1 4823 _cleanup_free_ char *line = NULL;
d35fbf6b 4824 pid_t pid;
8351ceae 4825
f2341e0a 4826 assert(unit);
d35fbf6b
DM
4827 assert(command);
4828 assert(context);
4829 assert(ret);
4830 assert(params);
25b583d7 4831 assert(params->fds || (params->n_socket_fds + params->n_storage_fds <= 0));
4298d0b5 4832
d35fbf6b
DM
4833 if (context->std_input == EXEC_INPUT_SOCKET ||
4834 context->std_output == EXEC_OUTPUT_SOCKET ||
4835 context->std_error == EXEC_OUTPUT_SOCKET) {
17df7223 4836
d85ff944
YW
4837 if (params->n_socket_fds > 1)
4838 return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EINVAL), "Got more than one socket.");
eef65bf3 4839
d85ff944
YW
4840 if (params->n_socket_fds == 0)
4841 return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EINVAL), "Got no socket.");
488ab41c 4842
d35fbf6b
DM
4843 socket_fd = params->fds[0];
4844 } else {
4845 socket_fd = -1;
4846 fds = params->fds;
9b141911 4847 n_socket_fds = params->n_socket_fds;
25b583d7 4848 n_storage_fds = params->n_storage_fds;
d35fbf6b 4849 }
94f04347 4850
34cf6c43 4851 r = exec_context_named_iofds(context, params, named_iofds);
52c239d7
LB
4852 if (r < 0)
4853 return log_unit_error_errno(unit, r, "Failed to load a named file descriptor: %m");
4854
f2341e0a 4855 r = exec_context_load_environment(unit, context, &files_env);
ff0af2a1 4856 if (r < 0)
f2341e0a 4857 return log_unit_error_errno(unit, r, "Failed to load environment files: %m");
034c6ed7 4858
8a62620e 4859 line = quote_command_line(command->argv);
d35fbf6b
DM
4860 if (!line)
4861 return log_oom();
fab56fc5 4862
9f71ba8d
ZJS
4863 /* Fork with up-to-date SELinux label database, so the child inherits the up-to-date db
4864 and, until the next SELinux policy changes, we save further reloads in future children. */
2df2152c
CG
4865 mac_selinux_maybe_reload();
4866
c2503e35
RH
4867 log_unit_struct(unit, LOG_DEBUG,
4868 LOG_UNIT_MESSAGE(unit, "About to execute %s", line),
4869 "EXECUTABLE=%s", command->path, /* We won't know the real executable path until we create
4870 the mount namespace in the child, but we want to log
4871 from the parent, so we need to use the (possibly
4872 inaccurate) path here. */
4873 LOG_UNIT_INVOCATION_ID(unit));
12145637 4874
78f93209
LP
4875 if (params->cgroup_path) {
4876 r = exec_parameters_get_cgroup_path(params, &subcgroup_path);
4877 if (r < 0)
4878 return log_unit_error_errno(unit, r, "Failed to acquire subcgroup path: %m");
4879 if (r > 0) { /* We are using a child cgroup */
4880 r = cg_create(SYSTEMD_CGROUP_CONTROLLER, subcgroup_path);
4881 if (r < 0)
4882 return log_unit_error_errno(unit, r, "Failed to create control group '%s': %m", subcgroup_path);
4e806bfa
AZ
4883
4884 /* Normally we would not propagate the oomd xattrs to children but since we created this
4885 * sub-cgroup internally we should do it. */
4886 cgroup_oomd_xattr_apply(unit, subcgroup_path);
78f93209
LP
4887 }
4888 }
4889
d35fbf6b
DM
4890 pid = fork();
4891 if (pid < 0)
74129a12 4892 return log_unit_error_errno(unit, errno, "Failed to fork: %m");
d35fbf6b
DM
4893
4894 if (pid == 0) {
12145637 4895 int exit_status = EXIT_SUCCESS;
ff0af2a1 4896
f2341e0a
LP
4897 r = exec_child(unit,
4898 command,
ff0af2a1
LP
4899 context,
4900 params,
4901 runtime,
29206d46 4902 dcreds,
ff0af2a1 4903 socket_fd,
52c239d7 4904 named_iofds,
4c47affc 4905 fds,
9b141911 4906 n_socket_fds,
25b583d7 4907 n_storage_fds,
ff0af2a1 4908 files_env,
00d9ef85 4909 unit->manager->user_lookup_fds[1],
12145637
LP
4910 &exit_status);
4911
e1714f02
ZJS
4912 if (r < 0) {
4913 const char *status =
4914 exit_status_to_string(exit_status,
e04ed6db 4915 EXIT_STATUS_LIBC | EXIT_STATUS_SYSTEMD);
e1714f02 4916
c2503e35
RH
4917 log_unit_struct_errno(unit, LOG_ERR, r,
4918 "MESSAGE_ID=" SD_MESSAGE_SPAWN_FAILED_STR,
4919 LOG_UNIT_INVOCATION_ID(unit),
4920 LOG_UNIT_MESSAGE(unit, "Failed at step %s spawning %s: %m",
4921 status, command->path),
4922 "EXECUTABLE=%s", command->path);
e1714f02 4923 }
4c2630eb 4924
ff0af2a1 4925 _exit(exit_status);
034c6ed7
LP
4926 }
4927
f2341e0a 4928 log_unit_debug(unit, "Forked %s as "PID_FMT, command->path, pid);
23635a85 4929
78f93209
LP
4930 /* We add the new process to the cgroup both in the child (so that we can be sure that no user code is ever
4931 * executed outside of the cgroup) and in the parent (so that we can be sure that when we kill the cgroup the
4932 * process will be killed too). */
4933 if (subcgroup_path)
4934 (void) cg_attach(SYSTEMD_CGROUP_CONTROLLER, subcgroup_path, pid);
2da3263a 4935
b58b4116 4936 exec_status_start(&command->exec_status, pid);
9fb86720 4937
034c6ed7 4938 *ret = pid;
5cb5a6ff
LP
4939 return 0;
4940}
4941
034c6ed7
LP
4942void exec_context_init(ExecContext *c) {
4943 assert(c);
4944
4c12626c 4945 c->umask = 0022;
5bead76e 4946 c->ioprio = ioprio_prio_value(IOPRIO_CLASS_BE, 0);
94f04347 4947 c->cpu_sched_policy = SCHED_OTHER;
071830ff 4948 c->syslog_priority = LOG_DAEMON|LOG_INFO;
74922904 4949 c->syslog_level_prefix = true;
353e12c2 4950 c->ignore_sigpipe = true;
3a43da28 4951 c->timer_slack_nsec = NSEC_INFINITY;
050f7277 4952 c->personality = PERSONALITY_INVALID;
5b10116e
ZJS
4953 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++)
4954 c->directories[t].mode = 0755;
12213aed 4955 c->timeout_clean_usec = USEC_INFINITY;
a103496c 4956 c->capability_bounding_set = CAP_ALL;
aa9d574d
YW
4957 assert_cc(NAMESPACE_FLAGS_INITIAL != NAMESPACE_FLAGS_ALL);
4958 c->restrict_namespaces = NAMESPACE_FLAGS_INITIAL;
d3070fbd 4959 c->log_level_max = -1;
005bfaf1
TM
4960#if HAVE_SECCOMP
4961 c->syscall_errno = SECCOMP_ERROR_NUMBER_KILL;
4962#endif
b070c7c0 4963 numa_policy_reset(&c->numa_policy);
034c6ed7
LP
4964}
4965
613b411c 4966void exec_context_done(ExecContext *c) {
5cb5a6ff
LP
4967 assert(c);
4968
6796073e
LP
4969 c->environment = strv_free(c->environment);
4970 c->environment_files = strv_free(c->environment_files);
b4c14404 4971 c->pass_environment = strv_free(c->pass_environment);
00819cc1 4972 c->unset_environment = strv_free(c->unset_environment);
8c7be95e 4973
31ce987c 4974 rlimit_free_all(c->rlimit);
034c6ed7 4975
5b10116e 4976 for (size_t l = 0; l < 3; l++) {
52c239d7 4977 c->stdio_fdname[l] = mfree(c->stdio_fdname[l]);
2038c3f5
LP
4978 c->stdio_file[l] = mfree(c->stdio_file[l]);
4979 }
52c239d7 4980
a1e58e8e
LP
4981 c->working_directory = mfree(c->working_directory);
4982 c->root_directory = mfree(c->root_directory);
915e6d16 4983 c->root_image = mfree(c->root_image);
18d73705 4984 c->root_image_options = mount_options_free_all(c->root_image_options);
0389f4fa
LB
4985 c->root_hash = mfree(c->root_hash);
4986 c->root_hash_size = 0;
4987 c->root_hash_path = mfree(c->root_hash_path);
d4d55b0d
LB
4988 c->root_hash_sig = mfree(c->root_hash_sig);
4989 c->root_hash_sig_size = 0;
4990 c->root_hash_sig_path = mfree(c->root_hash_sig_path);
0389f4fa 4991 c->root_verity = mfree(c->root_verity);
93f59701 4992 c->extension_images = mount_image_free_many(c->extension_images, &c->n_extension_images);
a1e58e8e
LP
4993 c->tty_path = mfree(c->tty_path);
4994 c->syslog_identifier = mfree(c->syslog_identifier);
4995 c->user = mfree(c->user);
4996 c->group = mfree(c->group);
034c6ed7 4997
6796073e 4998 c->supplementary_groups = strv_free(c->supplementary_groups);
94f04347 4999
a1e58e8e 5000 c->pam_name = mfree(c->pam_name);
5b6319dc 5001
2a624c36
AP
5002 c->read_only_paths = strv_free(c->read_only_paths);
5003 c->read_write_paths = strv_free(c->read_write_paths);
5004 c->inaccessible_paths = strv_free(c->inaccessible_paths);
ddc155b2
TM
5005 c->exec_paths = strv_free(c->exec_paths);
5006 c->no_exec_paths = strv_free(c->no_exec_paths);
8c35c10d 5007 c->exec_search_path = strv_free(c->exec_search_path);
82c121a4 5008
d2d6c096 5009 bind_mount_free_many(c->bind_mounts, c->n_bind_mounts);
8e06d57c
YW
5010 c->bind_mounts = NULL;
5011 c->n_bind_mounts = 0;
2abd4e38
YW
5012 temporary_filesystem_free_many(c->temporary_filesystems, c->n_temporary_filesystems);
5013 c->temporary_filesystems = NULL;
5014 c->n_temporary_filesystems = 0;
b3d13314 5015 c->mount_images = mount_image_free_many(c->mount_images, &c->n_mount_images);
d2d6c096 5016
0985c7c4 5017 cpu_set_reset(&c->cpu_set);
b070c7c0 5018 numa_policy_reset(&c->numa_policy);
86a3475b 5019
a1e58e8e
LP
5020 c->utmp_id = mfree(c->utmp_id);
5021 c->selinux_context = mfree(c->selinux_context);
5022 c->apparmor_profile = mfree(c->apparmor_profile);
5b8e1b77 5023 c->smack_process_label = mfree(c->smack_process_label);
eef65bf3 5024
b1994387
ILG
5025 c->restrict_filesystems = set_free(c->restrict_filesystems);
5026
8cfa775f 5027 c->syscall_filter = hashmap_free(c->syscall_filter);
525d3cc7
LP
5028 c->syscall_archs = set_free(c->syscall_archs);
5029 c->address_families = set_free(c->address_families);
e66cf1a3 5030
5b10116e
ZJS
5031 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++)
5032 c->directories[t].paths = strv_free(c->directories[t].paths);
d3070fbd
LP
5033
5034 c->log_level_max = -1;
5035
5036 exec_context_free_log_extra_fields(c);
08f3be7a 5037
5ac1530e
ZJS
5038 c->log_ratelimit_interval_usec = 0;
5039 c->log_ratelimit_burst = 0;
90fc172e 5040
08f3be7a
LP
5041 c->stdin_data = mfree(c->stdin_data);
5042 c->stdin_data_size = 0;
a8d08f39
LP
5043
5044 c->network_namespace_path = mfree(c->network_namespace_path);
71d1e583 5045 c->ipc_namespace_path = mfree(c->ipc_namespace_path);
91dd5f7c
LP
5046
5047 c->log_namespace = mfree(c->log_namespace);
bb0c0d6f 5048
43144be4 5049 c->load_credentials = hashmap_free(c->load_credentials);
bb0c0d6f 5050 c->set_credentials = hashmap_free(c->set_credentials);
e66cf1a3
LP
5051}
5052
34cf6c43 5053int exec_context_destroy_runtime_directory(const ExecContext *c, const char *runtime_prefix) {
e66cf1a3
LP
5054 char **i;
5055
5056 assert(c);
5057
5058 if (!runtime_prefix)
5059 return 0;
5060
3536f49e 5061 STRV_FOREACH(i, c->directories[EXEC_DIRECTORY_RUNTIME].paths) {
c2b2df60 5062 _cleanup_free_ char *p = NULL;
e66cf1a3 5063
494d0247
YW
5064 if (exec_directory_is_private(c, EXEC_DIRECTORY_RUNTIME))
5065 p = path_join(runtime_prefix, "private", *i);
5066 else
5067 p = path_join(runtime_prefix, *i);
e66cf1a3
LP
5068 if (!p)
5069 return -ENOMEM;
5070
7bc4bf4a
LP
5071 /* We execute this synchronously, since we need to be sure this is gone when we start the
5072 * service next. */
c6878637 5073 (void) rm_rf(p, REMOVE_ROOT);
e66cf1a3
LP
5074 }
5075
5076 return 0;
5cb5a6ff
LP
5077}
5078
bb0c0d6f
LP
5079int exec_context_destroy_credentials(const ExecContext *c, const char *runtime_prefix, const char *unit) {
5080 _cleanup_free_ char *p = NULL;
5081
5082 assert(c);
5083
5084 if (!runtime_prefix || !unit)
5085 return 0;
5086
5087 p = path_join(runtime_prefix, "credentials", unit);
5088 if (!p)
5089 return -ENOMEM;
5090
5091 /* This is either a tmpfs/ramfs of its own, or a plain directory. Either way, let's first try to
5092 * unmount it, and afterwards remove the mount point */
5093 (void) umount2(p, MNT_DETACH|UMOUNT_NOFOLLOW);
5094 (void) rm_rf(p, REMOVE_ROOT|REMOVE_CHMOD);
5095
5096 return 0;
5097}
5098
34cf6c43 5099static void exec_command_done(ExecCommand *c) {
43d0fcbd
LP
5100 assert(c);
5101
a1e58e8e 5102 c->path = mfree(c->path);
6796073e 5103 c->argv = strv_free(c->argv);
43d0fcbd
LP
5104}
5105
da6053d0 5106void exec_command_done_array(ExecCommand *c, size_t n) {
fe96c0f8 5107 for (size_t i = 0; i < n; i++)
43d0fcbd
LP
5108 exec_command_done(c+i);
5109}
5110
f1acf85a 5111ExecCommand* exec_command_free_list(ExecCommand *c) {
5cb5a6ff
LP
5112 ExecCommand *i;
5113
5114 while ((i = c)) {
71fda00f 5115 LIST_REMOVE(command, c, i);
43d0fcbd 5116 exec_command_done(i);
5cb5a6ff
LP
5117 free(i);
5118 }
f1acf85a
ZJS
5119
5120 return NULL;
5cb5a6ff
LP
5121}
5122
da6053d0 5123void exec_command_free_array(ExecCommand **c, size_t n) {
5b10116e 5124 for (size_t i = 0; i < n; i++)
f1acf85a 5125 c[i] = exec_command_free_list(c[i]);
034c6ed7
LP
5126}
5127
6a1d4d9f 5128void exec_command_reset_status_array(ExecCommand *c, size_t n) {
5b10116e 5129 for (size_t i = 0; i < n; i++)
6a1d4d9f
LP
5130 exec_status_reset(&c[i].exec_status);
5131}
5132
5133void exec_command_reset_status_list_array(ExecCommand **c, size_t n) {
5b10116e 5134 for (size_t i = 0; i < n; i++) {
6a1d4d9f
LP
5135 ExecCommand *z;
5136
5137 LIST_FOREACH(command, z, c[i])
5138 exec_status_reset(&z->exec_status);
5139 }
5140}
5141
039f0e70 5142typedef struct InvalidEnvInfo {
34cf6c43 5143 const Unit *unit;
039f0e70
LP
5144 const char *path;
5145} InvalidEnvInfo;
5146
5147static void invalid_env(const char *p, void *userdata) {
5148 InvalidEnvInfo *info = userdata;
5149
f2341e0a 5150 log_unit_error(info->unit, "Ignoring invalid environment assignment '%s': %s", p, info->path);
039f0e70
LP
5151}
5152
52c239d7
LB
5153const char* exec_context_fdname(const ExecContext *c, int fd_index) {
5154 assert(c);
5155
5156 switch (fd_index) {
5073ff6b 5157
52c239d7
LB
5158 case STDIN_FILENO:
5159 if (c->std_input != EXEC_INPUT_NAMED_FD)
5160 return NULL;
5073ff6b 5161
52c239d7 5162 return c->stdio_fdname[STDIN_FILENO] ?: "stdin";
5073ff6b 5163
52c239d7
LB
5164 case STDOUT_FILENO:
5165 if (c->std_output != EXEC_OUTPUT_NAMED_FD)
5166 return NULL;
5073ff6b 5167
52c239d7 5168 return c->stdio_fdname[STDOUT_FILENO] ?: "stdout";
5073ff6b 5169
52c239d7
LB
5170 case STDERR_FILENO:
5171 if (c->std_error != EXEC_OUTPUT_NAMED_FD)
5172 return NULL;
5073ff6b 5173
52c239d7 5174 return c->stdio_fdname[STDERR_FILENO] ?: "stderr";
5073ff6b 5175
52c239d7
LB
5176 default:
5177 return NULL;
5178 }
5179}
5180
2caa38e9
LP
5181static int exec_context_named_iofds(
5182 const ExecContext *c,
5183 const ExecParameters *p,
5184 int named_iofds[static 3]) {
5185
5b10116e 5186 size_t targets;
56fbd561 5187 const char* stdio_fdname[3];
da6053d0 5188 size_t n_fds;
52c239d7
LB
5189
5190 assert(c);
5191 assert(p);
2caa38e9 5192 assert(named_iofds);
52c239d7
LB
5193
5194 targets = (c->std_input == EXEC_INPUT_NAMED_FD) +
5195 (c->std_output == EXEC_OUTPUT_NAMED_FD) +
5196 (c->std_error == EXEC_OUTPUT_NAMED_FD);
5197
5b10116e 5198 for (size_t i = 0; i < 3; i++)
52c239d7
LB
5199 stdio_fdname[i] = exec_context_fdname(c, i);
5200
4c47affc
FB
5201 n_fds = p->n_storage_fds + p->n_socket_fds;
5202
5b10116e 5203 for (size_t i = 0; i < n_fds && targets > 0; i++)
56fbd561
ZJS
5204 if (named_iofds[STDIN_FILENO] < 0 &&
5205 c->std_input == EXEC_INPUT_NAMED_FD &&
5206 stdio_fdname[STDIN_FILENO] &&
5207 streq(p->fd_names[i], stdio_fdname[STDIN_FILENO])) {
5208
52c239d7
LB
5209 named_iofds[STDIN_FILENO] = p->fds[i];
5210 targets--;
56fbd561
ZJS
5211
5212 } else if (named_iofds[STDOUT_FILENO] < 0 &&
5213 c->std_output == EXEC_OUTPUT_NAMED_FD &&
5214 stdio_fdname[STDOUT_FILENO] &&
5215 streq(p->fd_names[i], stdio_fdname[STDOUT_FILENO])) {
5216
52c239d7
LB
5217 named_iofds[STDOUT_FILENO] = p->fds[i];
5218 targets--;
56fbd561
ZJS
5219
5220 } else if (named_iofds[STDERR_FILENO] < 0 &&
5221 c->std_error == EXEC_OUTPUT_NAMED_FD &&
5222 stdio_fdname[STDERR_FILENO] &&
5223 streq(p->fd_names[i], stdio_fdname[STDERR_FILENO])) {
5224
52c239d7
LB
5225 named_iofds[STDERR_FILENO] = p->fds[i];
5226 targets--;
5227 }
5228
56fbd561 5229 return targets == 0 ? 0 : -ENOENT;
52c239d7
LB
5230}
5231
34cf6c43 5232static int exec_context_load_environment(const Unit *unit, const ExecContext *c, char ***l) {
8c7be95e
LP
5233 char **i, **r = NULL;
5234
5235 assert(c);
5236 assert(l);
5237
5238 STRV_FOREACH(i, c->environment_files) {
5239 char *fn;
52511fae 5240 int k;
8c7be95e
LP
5241 bool ignore = false;
5242 char **p;
7fd1b19b 5243 _cleanup_globfree_ glob_t pglob = {};
8c7be95e
LP
5244
5245 fn = *i;
5246
5247 if (fn[0] == '-') {
5248 ignore = true;
313cefa1 5249 fn++;
8c7be95e
LP
5250 }
5251
5252 if (!path_is_absolute(fn)) {
8c7be95e
LP
5253 if (ignore)
5254 continue;
5255
5256 strv_free(r);
5257 return -EINVAL;
5258 }
5259
2bef10ab 5260 /* Filename supports globbing, take all matching files */
d8c92e8b
ZJS
5261 k = safe_glob(fn, 0, &pglob);
5262 if (k < 0) {
2bef10ab
PL
5263 if (ignore)
5264 continue;
8c7be95e 5265
2bef10ab 5266 strv_free(r);
d8c92e8b 5267 return k;
2bef10ab 5268 }
8c7be95e 5269
d8c92e8b
ZJS
5270 /* When we don't match anything, -ENOENT should be returned */
5271 assert(pglob.gl_pathc > 0);
5272
5b10116e 5273 for (unsigned n = 0; n < pglob.gl_pathc; n++) {
aa8fbc74 5274 k = load_env_file(NULL, pglob.gl_pathv[n], &p);
2bef10ab
PL
5275 if (k < 0) {
5276 if (ignore)
5277 continue;
8c7be95e 5278
2bef10ab 5279 strv_free(r);
2bef10ab 5280 return k;
e9c1ea9d 5281 }
ebc05a09 5282 /* Log invalid environment variables with filename */
039f0e70
LP
5283 if (p) {
5284 InvalidEnvInfo info = {
f2341e0a 5285 .unit = unit,
039f0e70
LP
5286 .path = pglob.gl_pathv[n]
5287 };
5288
5289 p = strv_env_clean_with_callback(p, invalid_env, &info);
5290 }
8c7be95e 5291
234519ae 5292 if (!r)
2bef10ab
PL
5293 r = p;
5294 else {
5295 char **m;
8c7be95e 5296
4ab3d29f 5297 m = strv_env_merge(r, p);
2bef10ab
PL
5298 strv_free(r);
5299 strv_free(p);
c84a9488 5300 if (!m)
2bef10ab 5301 return -ENOMEM;
2bef10ab
PL
5302
5303 r = m;
5304 }
8c7be95e
LP
5305 }
5306 }
5307
5308 *l = r;
5309
5310 return 0;
5311}
5312
6ac8fdc9 5313static bool tty_may_match_dev_console(const char *tty) {
7b912648 5314 _cleanup_free_ char *resolved = NULL;
6ac8fdc9 5315
1e22b5cd
LP
5316 if (!tty)
5317 return true;
5318
a119ec7c 5319 tty = skip_dev_prefix(tty);
6ac8fdc9
MS
5320
5321 /* trivial identity? */
5322 if (streq(tty, "console"))
5323 return true;
5324
7b912648
LP
5325 if (resolve_dev_console(&resolved) < 0)
5326 return true; /* if we could not resolve, assume it may */
6ac8fdc9
MS
5327
5328 /* "tty0" means the active VC, so it may be the same sometimes */
955f1c85 5329 return path_equal(resolved, tty) || (streq(resolved, "tty0") && tty_is_vc(tty));
6ac8fdc9
MS
5330}
5331
6c0ae739
LP
5332static bool exec_context_may_touch_tty(const ExecContext *ec) {
5333 assert(ec);
1e22b5cd 5334
6c0ae739 5335 return ec->tty_reset ||
1e22b5cd
LP
5336 ec->tty_vhangup ||
5337 ec->tty_vt_disallocate ||
6ac8fdc9
MS
5338 is_terminal_input(ec->std_input) ||
5339 is_terminal_output(ec->std_output) ||
6c0ae739
LP
5340 is_terminal_output(ec->std_error);
5341}
5342
5343bool exec_context_may_touch_console(const ExecContext *ec) {
5344
5345 return exec_context_may_touch_tty(ec) &&
1e22b5cd 5346 tty_may_match_dev_console(exec_context_tty_path(ec));
6ac8fdc9
MS
5347}
5348
15ae422b
LP
5349static void strv_fprintf(FILE *f, char **l) {
5350 char **g;
5351
5352 assert(f);
5353
5354 STRV_FOREACH(g, l)
5355 fprintf(f, " %s", *g);
5356}
5357
ddc155b2
TM
5358static void strv_dump(FILE* f, const char *prefix, const char *name, char **strv) {
5359 assert(f);
5360 assert(prefix);
5361 assert(name);
5362
5363 if (!strv_isempty(strv)) {
a7bd1656 5364 fprintf(f, "%s%s:", prefix, name);
ddc155b2
TM
5365 strv_fprintf(f, strv);
5366 fputs("\n", f);
5367 }
5368}
5369
34cf6c43 5370void exec_context_dump(const ExecContext *c, FILE* f, const char *prefix) {
5291f26d 5371 char **e, **d;
add00535 5372 int r;
9eba9da4 5373
5cb5a6ff
LP
5374 assert(c);
5375 assert(f);
5376
4ad49000 5377 prefix = strempty(prefix);
5cb5a6ff
LP
5378
5379 fprintf(f,
94f04347
LP
5380 "%sUMask: %04o\n"
5381 "%sWorkingDirectory: %s\n"
451a074f 5382 "%sRootDirectory: %s\n"
15ae422b 5383 "%sNonBlocking: %s\n"
64747e2d 5384 "%sPrivateTmp: %s\n"
7f112f50 5385 "%sPrivateDevices: %s\n"
59eeb84b 5386 "%sProtectKernelTunables: %s\n"
e66a2f65 5387 "%sProtectKernelModules: %s\n"
84703040 5388 "%sProtectKernelLogs: %s\n"
fc64760d 5389 "%sProtectClock: %s\n"
59eeb84b 5390 "%sProtectControlGroups: %s\n"
d251207d
LP
5391 "%sPrivateNetwork: %s\n"
5392 "%sPrivateUsers: %s\n"
1b8689f9
LP
5393 "%sProtectHome: %s\n"
5394 "%sProtectSystem: %s\n"
5d997827 5395 "%sMountAPIVFS: %s\n"
f3e43635 5396 "%sIgnoreSIGPIPE: %s\n"
f4170c67 5397 "%sMemoryDenyWriteExecute: %s\n"
b1edf445 5398 "%sRestrictRealtime: %s\n"
f69567cb 5399 "%sRestrictSUIDSGID: %s\n"
aecd5ac6 5400 "%sKeyringMode: %s\n"
4e399953
LP
5401 "%sProtectHostname: %s\n"
5402 "%sProtectProc: %s\n"
5403 "%sProcSubset: %s\n",
5cb5a6ff 5404 prefix, c->umask,
14eb3285
LP
5405 prefix, empty_to_root(c->working_directory),
5406 prefix, empty_to_root(c->root_directory),
15ae422b 5407 prefix, yes_no(c->non_blocking),
64747e2d 5408 prefix, yes_no(c->private_tmp),
7f112f50 5409 prefix, yes_no(c->private_devices),
59eeb84b 5410 prefix, yes_no(c->protect_kernel_tunables),
e66a2f65 5411 prefix, yes_no(c->protect_kernel_modules),
84703040 5412 prefix, yes_no(c->protect_kernel_logs),
fc64760d 5413 prefix, yes_no(c->protect_clock),
59eeb84b 5414 prefix, yes_no(c->protect_control_groups),
d251207d
LP
5415 prefix, yes_no(c->private_network),
5416 prefix, yes_no(c->private_users),
1b8689f9
LP
5417 prefix, protect_home_to_string(c->protect_home),
5418 prefix, protect_system_to_string(c->protect_system),
5e98086d 5419 prefix, yes_no(exec_context_get_effective_mount_apivfs(c)),
f3e43635 5420 prefix, yes_no(c->ignore_sigpipe),
f4170c67 5421 prefix, yes_no(c->memory_deny_write_execute),
b1edf445 5422 prefix, yes_no(c->restrict_realtime),
f69567cb 5423 prefix, yes_no(c->restrict_suid_sgid),
aecd5ac6 5424 prefix, exec_keyring_mode_to_string(c->keyring_mode),
4e399953
LP
5425 prefix, yes_no(c->protect_hostname),
5426 prefix, protect_proc_to_string(c->protect_proc),
5427 prefix, proc_subset_to_string(c->proc_subset));
fb33a393 5428
915e6d16
LP
5429 if (c->root_image)
5430 fprintf(f, "%sRootImage: %s\n", prefix, c->root_image);
5431
18d73705
LB
5432 if (c->root_image_options) {
5433 MountOptions *o;
5434
5435 fprintf(f, "%sRootImageOptions:", prefix);
5436 LIST_FOREACH(mount_options, o, c->root_image_options)
5437 if (!isempty(o->options))
9ece6444
LB
5438 fprintf(f, " %s:%s",
5439 partition_designator_to_string(o->partition_designator),
5440 o->options);
18d73705
LB
5441 fprintf(f, "\n");
5442 }
5443
0389f4fa
LB
5444 if (c->root_hash) {
5445 _cleanup_free_ char *encoded = NULL;
5446 encoded = hexmem(c->root_hash, c->root_hash_size);
5447 if (encoded)
5448 fprintf(f, "%sRootHash: %s\n", prefix, encoded);
5449 }
5450
5451 if (c->root_hash_path)
5452 fprintf(f, "%sRootHash: %s\n", prefix, c->root_hash_path);
5453
d4d55b0d
LB
5454 if (c->root_hash_sig) {
5455 _cleanup_free_ char *encoded = NULL;
5456 ssize_t len;
5457 len = base64mem(c->root_hash_sig, c->root_hash_sig_size, &encoded);
5458 if (len)
5459 fprintf(f, "%sRootHashSignature: base64:%s\n", prefix, encoded);
5460 }
5461
5462 if (c->root_hash_sig_path)
5463 fprintf(f, "%sRootHashSignature: %s\n", prefix, c->root_hash_sig_path);
5464
0389f4fa
LB
5465 if (c->root_verity)
5466 fprintf(f, "%sRootVerity: %s\n", prefix, c->root_verity);
5467
8c7be95e
LP
5468 STRV_FOREACH(e, c->environment)
5469 fprintf(f, "%sEnvironment: %s\n", prefix, *e);
5470
5471 STRV_FOREACH(e, c->environment_files)
5472 fprintf(f, "%sEnvironmentFile: %s\n", prefix, *e);
94f04347 5473
b4c14404
FB
5474 STRV_FOREACH(e, c->pass_environment)
5475 fprintf(f, "%sPassEnvironment: %s\n", prefix, *e);
5476
00819cc1
LP
5477 STRV_FOREACH(e, c->unset_environment)
5478 fprintf(f, "%sUnsetEnvironment: %s\n", prefix, *e);
5479
53f47dfc
YW
5480 fprintf(f, "%sRuntimeDirectoryPreserve: %s\n", prefix, exec_preserve_mode_to_string(c->runtime_directory_preserve_mode));
5481
5b10116e 5482 for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
3536f49e
YW
5483 fprintf(f, "%s%sMode: %04o\n", prefix, exec_directory_type_to_string(dt), c->directories[dt].mode);
5484
5485 STRV_FOREACH(d, c->directories[dt].paths)
5486 fprintf(f, "%s%s: %s\n", prefix, exec_directory_type_to_string(dt), *d);
5487 }
c2bbd90b 5488
5291f26d 5489 fprintf(f, "%sTimeoutCleanSec: %s\n", prefix, FORMAT_TIMESPAN(c->timeout_clean_usec, USEC_PER_SEC));
12213aed 5490
fb33a393 5491 if (c->nice_set)
5291f26d 5492 fprintf(f, "%sNice: %i\n", prefix, c->nice);
fb33a393 5493
dd6c17b1 5494 if (c->oom_score_adjust_set)
5291f26d 5495 fprintf(f, "%sOOMScoreAdjust: %i\n", prefix, c->oom_score_adjust);
9eba9da4 5496
ad21e542 5497 if (c->coredump_filter_set)
5291f26d 5498 fprintf(f, "%sCoredumpFilter: 0x%"PRIx64"\n", prefix, c->coredump_filter);
ad21e542 5499
5b10116e 5500 for (unsigned i = 0; i < RLIM_NLIMITS; i++)
3c11da9d 5501 if (c->rlimit[i]) {
4c3a2b84 5502 fprintf(f, "%sLimit%s: " RLIM_FMT "\n",
3c11da9d 5503 prefix, rlimit_to_string(i), c->rlimit[i]->rlim_max);
4c3a2b84 5504 fprintf(f, "%sLimit%sSoft: " RLIM_FMT "\n",
3c11da9d
EV
5505 prefix, rlimit_to_string(i), c->rlimit[i]->rlim_cur);
5506 }
94f04347 5507
f8b69d1d 5508 if (c->ioprio_set) {
1756a011 5509 _cleanup_free_ char *class_str = NULL;
f8b69d1d 5510
5bead76e 5511 r = ioprio_class_to_string_alloc(ioprio_prio_class(c->ioprio), &class_str);
837df140
YW
5512 if (r >= 0)
5513 fprintf(f, "%sIOSchedulingClass: %s\n", prefix, class_str);
5514
5bead76e 5515 fprintf(f, "%sIOPriority: %d\n", prefix, ioprio_prio_data(c->ioprio));
f8b69d1d 5516 }
94f04347 5517
f8b69d1d 5518 if (c->cpu_sched_set) {
1756a011 5519 _cleanup_free_ char *policy_str = NULL;
f8b69d1d 5520
837df140
YW
5521 r = sched_policy_to_string_alloc(c->cpu_sched_policy, &policy_str);
5522 if (r >= 0)
5523 fprintf(f, "%sCPUSchedulingPolicy: %s\n", prefix, policy_str);
5524
94f04347 5525 fprintf(f,
38b48754
LP
5526 "%sCPUSchedulingPriority: %i\n"
5527 "%sCPUSchedulingResetOnFork: %s\n",
38b48754
LP
5528 prefix, c->cpu_sched_priority,
5529 prefix, yes_no(c->cpu_sched_reset_on_fork));
b929bf04 5530 }
94f04347 5531
0985c7c4 5532 if (c->cpu_set.set) {
e7fca352
MS
5533 _cleanup_free_ char *affinity = NULL;
5534
5535 affinity = cpu_set_to_range_string(&c->cpu_set);
5536 fprintf(f, "%sCPUAffinity: %s\n", prefix, affinity);
94f04347
LP
5537 }
5538
b070c7c0
MS
5539 if (mpol_is_valid(numa_policy_get_type(&c->numa_policy))) {
5540 _cleanup_free_ char *nodes = NULL;
5541
5542 nodes = cpu_set_to_range_string(&c->numa_policy.nodes);
5543 fprintf(f, "%sNUMAPolicy: %s\n", prefix, mpol_to_string(numa_policy_get_type(&c->numa_policy)));
5544 fprintf(f, "%sNUMAMask: %s\n", prefix, strnull(nodes));
5545 }
5546
3a43da28 5547 if (c->timer_slack_nsec != NSEC_INFINITY)
ccd06097 5548 fprintf(f, "%sTimerSlackNSec: "NSEC_FMT "\n", prefix, c->timer_slack_nsec);
94f04347
LP
5549
5550 fprintf(f,
80876c20
LP
5551 "%sStandardInput: %s\n"
5552 "%sStandardOutput: %s\n"
5553 "%sStandardError: %s\n",
5554 prefix, exec_input_to_string(c->std_input),
5555 prefix, exec_output_to_string(c->std_output),
5556 prefix, exec_output_to_string(c->std_error));
5557
befc4a80
LP
5558 if (c->std_input == EXEC_INPUT_NAMED_FD)
5559 fprintf(f, "%sStandardInputFileDescriptorName: %s\n", prefix, c->stdio_fdname[STDIN_FILENO]);
5560 if (c->std_output == EXEC_OUTPUT_NAMED_FD)
5561 fprintf(f, "%sStandardOutputFileDescriptorName: %s\n", prefix, c->stdio_fdname[STDOUT_FILENO]);
5562 if (c->std_error == EXEC_OUTPUT_NAMED_FD)
5563 fprintf(f, "%sStandardErrorFileDescriptorName: %s\n", prefix, c->stdio_fdname[STDERR_FILENO]);
5564
5565 if (c->std_input == EXEC_INPUT_FILE)
5566 fprintf(f, "%sStandardInputFile: %s\n", prefix, c->stdio_file[STDIN_FILENO]);
5567 if (c->std_output == EXEC_OUTPUT_FILE)
5568 fprintf(f, "%sStandardOutputFile: %s\n", prefix, c->stdio_file[STDOUT_FILENO]);
566b7d23
ZD
5569 if (c->std_output == EXEC_OUTPUT_FILE_APPEND)
5570 fprintf(f, "%sStandardOutputFileToAppend: %s\n", prefix, c->stdio_file[STDOUT_FILENO]);
8d7dab1f
LW
5571 if (c->std_output == EXEC_OUTPUT_FILE_TRUNCATE)
5572 fprintf(f, "%sStandardOutputFileToTruncate: %s\n", prefix, c->stdio_file[STDOUT_FILENO]);
befc4a80
LP
5573 if (c->std_error == EXEC_OUTPUT_FILE)
5574 fprintf(f, "%sStandardErrorFile: %s\n", prefix, c->stdio_file[STDERR_FILENO]);
566b7d23
ZD
5575 if (c->std_error == EXEC_OUTPUT_FILE_APPEND)
5576 fprintf(f, "%sStandardErrorFileToAppend: %s\n", prefix, c->stdio_file[STDERR_FILENO]);
8d7dab1f
LW
5577 if (c->std_error == EXEC_OUTPUT_FILE_TRUNCATE)
5578 fprintf(f, "%sStandardErrorFileToTruncate: %s\n", prefix, c->stdio_file[STDERR_FILENO]);
befc4a80 5579
80876c20
LP
5580 if (c->tty_path)
5581 fprintf(f,
6ea832a2
LP
5582 "%sTTYPath: %s\n"
5583 "%sTTYReset: %s\n"
5584 "%sTTYVHangup: %s\n"
5585 "%sTTYVTDisallocate: %s\n",
5586 prefix, c->tty_path,
5587 prefix, yes_no(c->tty_reset),
5588 prefix, yes_no(c->tty_vhangup),
5589 prefix, yes_no(c->tty_vt_disallocate));
94f04347 5590
9f6444eb 5591 if (IN_SET(c->std_output,
9f6444eb
LP
5592 EXEC_OUTPUT_KMSG,
5593 EXEC_OUTPUT_JOURNAL,
9f6444eb
LP
5594 EXEC_OUTPUT_KMSG_AND_CONSOLE,
5595 EXEC_OUTPUT_JOURNAL_AND_CONSOLE) ||
5596 IN_SET(c->std_error,
9f6444eb
LP
5597 EXEC_OUTPUT_KMSG,
5598 EXEC_OUTPUT_JOURNAL,
9f6444eb
LP
5599 EXEC_OUTPUT_KMSG_AND_CONSOLE,
5600 EXEC_OUTPUT_JOURNAL_AND_CONSOLE)) {
f8b69d1d 5601
5ce70e5b 5602 _cleanup_free_ char *fac_str = NULL, *lvl_str = NULL;
f8b69d1d 5603
837df140
YW
5604 r = log_facility_unshifted_to_string_alloc(c->syslog_priority >> 3, &fac_str);
5605 if (r >= 0)
5606 fprintf(f, "%sSyslogFacility: %s\n", prefix, fac_str);
f8b69d1d 5607
837df140
YW
5608 r = log_level_to_string_alloc(LOG_PRI(c->syslog_priority), &lvl_str);
5609 if (r >= 0)
5610 fprintf(f, "%sSyslogLevel: %s\n", prefix, lvl_str);
f8b69d1d 5611 }
94f04347 5612
d3070fbd
LP
5613 if (c->log_level_max >= 0) {
5614 _cleanup_free_ char *t = NULL;
5615
5616 (void) log_level_to_string_alloc(c->log_level_max, &t);
5617
5618 fprintf(f, "%sLogLevelMax: %s\n", prefix, strna(t));
5619 }
5620
5291f26d 5621 if (c->log_ratelimit_interval_usec > 0)
90fc172e
AZ
5622 fprintf(f,
5623 "%sLogRateLimitIntervalSec: %s\n",
5291f26d 5624 prefix, FORMAT_TIMESPAN(c->log_ratelimit_interval_usec, USEC_PER_SEC));
90fc172e 5625
5ac1530e
ZJS
5626 if (c->log_ratelimit_burst > 0)
5627 fprintf(f, "%sLogRateLimitBurst: %u\n", prefix, c->log_ratelimit_burst);
90fc172e 5628
5b10116e
ZJS
5629 for (size_t j = 0; j < c->n_log_extra_fields; j++) {
5630 fprintf(f, "%sLogExtraFields: ", prefix);
5631 fwrite(c->log_extra_fields[j].iov_base,
5632 1, c->log_extra_fields[j].iov_len,
5633 f);
5634 fputc('\n', f);
d3070fbd
LP
5635 }
5636
91dd5f7c
LP
5637 if (c->log_namespace)
5638 fprintf(f, "%sLogNamespace: %s\n", prefix, c->log_namespace);
5639
07d46372
YW
5640 if (c->secure_bits) {
5641 _cleanup_free_ char *str = NULL;
5642
5643 r = secure_bits_to_string_alloc(c->secure_bits, &str);
5644 if (r >= 0)
5645 fprintf(f, "%sSecure Bits: %s\n", prefix, str);
5646 }
94f04347 5647
a103496c 5648 if (c->capability_bounding_set != CAP_ALL) {
dd1f5bd0 5649 _cleanup_free_ char *str = NULL;
94f04347 5650
dd1f5bd0
YW
5651 r = capability_set_to_string_alloc(c->capability_bounding_set, &str);
5652 if (r >= 0)
5653 fprintf(f, "%sCapabilityBoundingSet: %s\n", prefix, str);
755d4b67
IP
5654 }
5655
5656 if (c->capability_ambient_set != 0) {
dd1f5bd0 5657 _cleanup_free_ char *str = NULL;
755d4b67 5658
dd1f5bd0
YW
5659 r = capability_set_to_string_alloc(c->capability_ambient_set, &str);
5660 if (r >= 0)
5661 fprintf(f, "%sAmbientCapabilities: %s\n", prefix, str);
94f04347
LP
5662 }
5663
5664 if (c->user)
f2d3769a 5665 fprintf(f, "%sUser: %s\n", prefix, c->user);
94f04347 5666 if (c->group)
f2d3769a 5667 fprintf(f, "%sGroup: %s\n", prefix, c->group);
94f04347 5668
29206d46
LP
5669 fprintf(f, "%sDynamicUser: %s\n", prefix, yes_no(c->dynamic_user));
5670
ddc155b2 5671 strv_dump(f, prefix, "SupplementaryGroups", c->supplementary_groups);
94f04347 5672
5b6319dc 5673 if (c->pam_name)
f2d3769a 5674 fprintf(f, "%sPAMName: %s\n", prefix, c->pam_name);
5b6319dc 5675
ddc155b2
TM
5676 strv_dump(f, prefix, "ReadWritePaths", c->read_write_paths);
5677 strv_dump(f, prefix, "ReadOnlyPaths", c->read_only_paths);
5678 strv_dump(f, prefix, "InaccessiblePaths", c->inaccessible_paths);
5679 strv_dump(f, prefix, "ExecPaths", c->exec_paths);
5680 strv_dump(f, prefix, "NoExecPaths", c->no_exec_paths);
8c35c10d 5681 strv_dump(f, prefix, "ExecSearchPath", c->exec_search_path);
2e22afe9 5682
5b10116e
ZJS
5683 for (size_t i = 0; i < c->n_bind_mounts; i++)
5684 fprintf(f, "%s%s: %s%s:%s:%s\n", prefix,
5685 c->bind_mounts[i].read_only ? "BindReadOnlyPaths" : "BindPaths",
5686 c->bind_mounts[i].ignore_enoent ? "-": "",
5687 c->bind_mounts[i].source,
5688 c->bind_mounts[i].destination,
5689 c->bind_mounts[i].recursive ? "rbind" : "norbind");
d2d6c096 5690
5b10116e
ZJS
5691 for (size_t i = 0; i < c->n_temporary_filesystems; i++) {
5692 const TemporaryFileSystem *t = c->temporary_filesystems + i;
2abd4e38 5693
5b10116e
ZJS
5694 fprintf(f, "%sTemporaryFileSystem: %s%s%s\n", prefix,
5695 t->path,
5696 isempty(t->options) ? "" : ":",
5697 strempty(t->options));
5698 }
2abd4e38 5699
169c1bda
LP
5700 if (c->utmp_id)
5701 fprintf(f,
5702 "%sUtmpIdentifier: %s\n",
5703 prefix, c->utmp_id);
7b52a628
MS
5704
5705 if (c->selinux_context)
5706 fprintf(f,
5f8640fb
LP
5707 "%sSELinuxContext: %s%s\n",
5708 prefix, c->selinux_context_ignore ? "-" : "", c->selinux_context);
17df7223 5709
80c21aea
WC
5710 if (c->apparmor_profile)
5711 fprintf(f,
5712 "%sAppArmorProfile: %s%s\n",
5713 prefix, c->apparmor_profile_ignore ? "-" : "", c->apparmor_profile);
5714
5715 if (c->smack_process_label)
5716 fprintf(f,
5717 "%sSmackProcessLabel: %s%s\n",
5718 prefix, c->smack_process_label_ignore ? "-" : "", c->smack_process_label);
5719
050f7277 5720 if (c->personality != PERSONALITY_INVALID)
ac45f971
LP
5721 fprintf(f,
5722 "%sPersonality: %s\n",
5723 prefix, strna(personality_to_string(c->personality)));
5724
78e864e5
TM
5725 fprintf(f,
5726 "%sLockPersonality: %s\n",
5727 prefix, yes_no(c->lock_personality));
5728
17df7223 5729 if (c->syscall_filter) {
349cc4a5 5730#if HAVE_SECCOMP
8cfa775f 5731 void *id, *val;
17df7223 5732 bool first = true;
351a19b1 5733#endif
17df7223
LP
5734
5735 fprintf(f,
57183d11 5736 "%sSystemCallFilter: ",
17df7223
LP
5737 prefix);
5738
6b000af4 5739 if (!c->syscall_allow_list)
17df7223
LP
5740 fputc('~', f);
5741
349cc4a5 5742#if HAVE_SECCOMP
90e74a66 5743 HASHMAP_FOREACH_KEY(val, id, c->syscall_filter) {
17df7223 5744 _cleanup_free_ char *name = NULL;
8cfa775f
YW
5745 const char *errno_name = NULL;
5746 int num = PTR_TO_INT(val);
17df7223
LP
5747
5748 if (first)
5749 first = false;
5750 else
5751 fputc(' ', f);
5752
57183d11 5753 name = seccomp_syscall_resolve_num_arch(SCMP_ARCH_NATIVE, PTR_TO_INT(id) - 1);
17df7223 5754 fputs(strna(name), f);
8cfa775f
YW
5755
5756 if (num >= 0) {
005bfaf1 5757 errno_name = seccomp_errno_or_action_to_string(num);
8cfa775f
YW
5758 if (errno_name)
5759 fprintf(f, ":%s", errno_name);
5760 else
5761 fprintf(f, ":%d", num);
5762 }
17df7223 5763 }
351a19b1 5764#endif
17df7223
LP
5765
5766 fputc('\n', f);
5767 }
5768
57183d11 5769 if (c->syscall_archs) {
349cc4a5 5770#if HAVE_SECCOMP
57183d11
LP
5771 void *id;
5772#endif
5773
5774 fprintf(f,
5775 "%sSystemCallArchitectures:",
5776 prefix);
5777
349cc4a5 5778#if HAVE_SECCOMP
90e74a66 5779 SET_FOREACH(id, c->syscall_archs)
57183d11
LP
5780 fprintf(f, " %s", strna(seccomp_arch_to_string(PTR_TO_UINT32(id) - 1)));
5781#endif
5782 fputc('\n', f);
5783 }
5784
add00535
LP
5785 if (exec_context_restrict_namespaces_set(c)) {
5786 _cleanup_free_ char *s = NULL;
5787
86c2a9f1 5788 r = namespace_flags_to_string(c->restrict_namespaces, &s);
add00535
LP
5789 if (r >= 0)
5790 fprintf(f, "%sRestrictNamespaces: %s\n",
dd0395b5 5791 prefix, strna(s));
add00535
LP
5792 }
5793
b1994387
ILG
5794#if HAVE_LIBBPF
5795 if (exec_context_restrict_filesystems_set(c))
5796 SET_FOREACH(e, c->restrict_filesystems)
5797 fprintf(f, "%sRestrictFileSystems: %s\n", prefix, *e);
5798#endif
5799
a8d08f39
LP
5800 if (c->network_namespace_path)
5801 fprintf(f,
5802 "%sNetworkNamespacePath: %s\n",
5803 prefix, c->network_namespace_path);
5804
3df90f24 5805 if (c->syscall_errno > 0) {
005bfaf1 5806#if HAVE_SECCOMP
3df90f24 5807 const char *errno_name;
005bfaf1 5808#endif
3df90f24
YW
5809
5810 fprintf(f, "%sSystemCallErrorNumber: ", prefix);
5811
005bfaf1
TM
5812#if HAVE_SECCOMP
5813 errno_name = seccomp_errno_or_action_to_string(c->syscall_errno);
3df90f24 5814 if (errno_name)
005bfaf1 5815 fputs(errno_name, f);
3df90f24 5816 else
005bfaf1
TM
5817 fprintf(f, "%d", c->syscall_errno);
5818#endif
5819 fputc('\n', f);
3df90f24 5820 }
b3d13314 5821
5b10116e 5822 for (size_t i = 0; i < c->n_mount_images; i++) {
427353f6
LB
5823 MountOptions *o;
5824
79e20ceb 5825 fprintf(f, "%sMountImages: %s%s:%s", prefix,
b3d13314
LB
5826 c->mount_images[i].ignore_enoent ? "-": "",
5827 c->mount_images[i].source,
79e20ceb 5828 c->mount_images[i].destination);
427353f6 5829 LIST_FOREACH(mount_options, o, c->mount_images[i].mount_options)
79e20ceb 5830 fprintf(f, ":%s:%s",
427353f6 5831 partition_designator_to_string(o->partition_designator),
79e20ceb 5832 strempty(o->options));
427353f6
LB
5833 fprintf(f, "\n");
5834 }
93f59701
LB
5835
5836 for (size_t i = 0; i < c->n_extension_images; i++) {
5837 MountOptions *o;
5838
5839 fprintf(f, "%sExtensionImages: %s%s", prefix,
5840 c->extension_images[i].ignore_enoent ? "-": "",
5841 c->extension_images[i].source);
5842 LIST_FOREACH(mount_options, o, c->extension_images[i].mount_options)
5843 fprintf(f, ":%s:%s",
5844 partition_designator_to_string(o->partition_designator),
5845 strempty(o->options));
5846 fprintf(f, "\n");
5847 }
5cb5a6ff
LP
5848}
5849
34cf6c43 5850bool exec_context_maintains_privileges(const ExecContext *c) {
a931ad47
LP
5851 assert(c);
5852
61233823 5853 /* Returns true if the process forked off would run under
a931ad47
LP
5854 * an unchanged UID or as root. */
5855
5856 if (!c->user)
5857 return true;
5858
5859 if (streq(c->user, "root") || streq(c->user, "0"))
5860 return true;
5861
5862 return false;
5863}
5864
34cf6c43 5865int exec_context_get_effective_ioprio(const ExecContext *c) {
7f452159
LP
5866 int p;
5867
5868 assert(c);
5869
5870 if (c->ioprio_set)
5871 return c->ioprio;
5872
5873 p = ioprio_get(IOPRIO_WHO_PROCESS, 0);
5874 if (p < 0)
5bead76e 5875 return ioprio_prio_value(IOPRIO_CLASS_BE, 4);
7f452159
LP
5876
5877 return p;
5878}
5879
5e98086d
ZJS
5880bool exec_context_get_effective_mount_apivfs(const ExecContext *c) {
5881 assert(c);
5882
61198784 5883 /* Explicit setting wins */
5e98086d
ZJS
5884 if (c->mount_apivfs_set)
5885 return c->mount_apivfs;
5886
61198784 5887 /* Default to "yes" if root directory or image are specified */
74e12520 5888 if (exec_context_with_rootfs(c))
61198784
ZJS
5889 return true;
5890
5e98086d
ZJS
5891 return false;
5892}
5893
d3070fbd 5894void exec_context_free_log_extra_fields(ExecContext *c) {
d3070fbd
LP
5895 assert(c);
5896
5b10116e 5897 for (size_t l = 0; l < c->n_log_extra_fields; l++)
d3070fbd
LP
5898 free(c->log_extra_fields[l].iov_base);
5899 c->log_extra_fields = mfree(c->log_extra_fields);
5900 c->n_log_extra_fields = 0;
5901}
5902
6f765baf 5903void exec_context_revert_tty(ExecContext *c) {
0ba976e8
LP
5904 _cleanup_close_ int fd = -1;
5905 const char *path;
5906 struct stat st;
6f765baf
LP
5907 int r;
5908
5909 assert(c);
5910
5911 /* First, reset the TTY (possibly kicking everybody else from the TTY) */
5912 exec_context_tty_reset(c, NULL);
5913
5914 /* And then undo what chown_terminal() did earlier. Note that we only do this if we have a path
5915 * configured. If the TTY was passed to us as file descriptor we assume the TTY is opened and managed
5916 * by whoever passed it to us and thus knows better when and how to chmod()/chown() it back. */
0ba976e8
LP
5917 if (!exec_context_may_touch_tty(c))
5918 return;
6f765baf 5919
0ba976e8
LP
5920 path = exec_context_tty_path(c);
5921 if (!path)
5922 return;
6f765baf 5923
0ba976e8
LP
5924 fd = open(path, O_PATH|O_CLOEXEC);
5925 if (fd < 0)
5926 return (void) log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_WARNING, errno,
5927 "Failed to open TTY inode of '%s' to adjust ownership/access mode, ignoring: %m",
5928 path);
5929
5930 if (fstat(fd, &st) < 0)
5931 return (void) log_warning_errno(errno, "Failed to stat TTY '%s', ignoring: %m", path);
5932
5933 /* Let's add a superficial check that we only do this for stuff that looks like a TTY. We only check
5934 * if things are a character device, since a proper check either means we'd have to open the TTY and
5935 * use isatty(), but we'd rather not do that since opening TTYs comes with all kinds of side-effects
5936 * and is slow. Or we'd have to hardcode dev_t major information, which we'd rather avoid. Why bother
5937 * with this at all? → https://github.com/systemd/systemd/issues/19213 */
5938 if (!S_ISCHR(st.st_mode))
5939 return log_warning("Configured TTY '%s' is not actually a character device, ignoring.", path);
5940
5941 r = fchmod_and_chown(fd, TTY_MODE, 0, TTY_GID);
5942 if (r < 0)
5943 log_warning_errno(r, "Failed to reset TTY ownership/access mode of %s, ignoring: %m", path);
6f765baf
LP
5944}
5945
4c2f5842
LP
5946int exec_context_get_clean_directories(
5947 ExecContext *c,
5948 char **prefix,
5949 ExecCleanMask mask,
5950 char ***ret) {
5951
5952 _cleanup_strv_free_ char **l = NULL;
4c2f5842
LP
5953 int r;
5954
5955 assert(c);
5956 assert(prefix);
5957 assert(ret);
5958
5b10116e 5959 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
4c2f5842
LP
5960 char **i;
5961
5962 if (!FLAGS_SET(mask, 1U << t))
5963 continue;
5964
5965 if (!prefix[t])
5966 continue;
5967
5968 STRV_FOREACH(i, c->directories[t].paths) {
5969 char *j;
5970
5971 j = path_join(prefix[t], *i);
5972 if (!j)
5973 return -ENOMEM;
5974
5975 r = strv_consume(&l, j);
5976 if (r < 0)
5977 return r;
7f622a19
YW
5978
5979 /* Also remove private directories unconditionally. */
5980 if (t != EXEC_DIRECTORY_CONFIGURATION) {
5981 j = path_join(prefix[t], "private", *i);
5982 if (!j)
5983 return -ENOMEM;
5984
5985 r = strv_consume(&l, j);
5986 if (r < 0)
5987 return r;
5988 }
4c2f5842
LP
5989 }
5990 }
5991
5992 *ret = TAKE_PTR(l);
5993 return 0;
5994}
5995
5996int exec_context_get_clean_mask(ExecContext *c, ExecCleanMask *ret) {
5997 ExecCleanMask mask = 0;
5998
5999 assert(c);
6000 assert(ret);
6001
6002 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++)
6003 if (!strv_isempty(c->directories[t].paths))
6004 mask |= 1U << t;
6005
6006 *ret = mask;
6007 return 0;
6008}
6009
b58b4116 6010void exec_status_start(ExecStatus *s, pid_t pid) {
034c6ed7 6011 assert(s);
5cb5a6ff 6012
2ed26ed0
LP
6013 *s = (ExecStatus) {
6014 .pid = pid,
6015 };
6016
b58b4116
LP
6017 dual_timestamp_get(&s->start_timestamp);
6018}
6019
34cf6c43 6020void exec_status_exit(ExecStatus *s, const ExecContext *context, pid_t pid, int code, int status) {
b58b4116
LP
6021 assert(s);
6022
d46b79bb 6023 if (s->pid != pid)
2ed26ed0
LP
6024 *s = (ExecStatus) {
6025 .pid = pid,
6026 };
b58b4116 6027
63983207 6028 dual_timestamp_get(&s->exit_timestamp);
9fb86720 6029
034c6ed7
LP
6030 s->code = code;
6031 s->status = status;
169c1bda 6032
6f765baf
LP
6033 if (context && context->utmp_id)
6034 (void) utmp_put_dead_process(context->utmp_id, pid, code, status);
9fb86720
LP
6035}
6036
6a1d4d9f
LP
6037void exec_status_reset(ExecStatus *s) {
6038 assert(s);
6039
6040 *s = (ExecStatus) {};
6041}
6042
34cf6c43 6043void exec_status_dump(const ExecStatus *s, FILE *f, const char *prefix) {
9fb86720
LP
6044 assert(s);
6045 assert(f);
6046
9fb86720
LP
6047 if (s->pid <= 0)
6048 return;
6049
4c940960
LP
6050 prefix = strempty(prefix);
6051
9fb86720 6052 fprintf(f,
ccd06097
ZJS
6053 "%sPID: "PID_FMT"\n",
6054 prefix, s->pid);
9fb86720 6055
af9d16e1 6056 if (dual_timestamp_is_set(&s->start_timestamp))
9fb86720
LP
6057 fprintf(f,
6058 "%sStart Timestamp: %s\n",
04f5c018 6059 prefix, FORMAT_TIMESTAMP(s->start_timestamp.realtime));
9fb86720 6060
af9d16e1 6061 if (dual_timestamp_is_set(&s->exit_timestamp))
9fb86720
LP
6062 fprintf(f,
6063 "%sExit Timestamp: %s\n"
6064 "%sExit Code: %s\n"
6065 "%sExit Status: %i\n",
04f5c018 6066 prefix, FORMAT_TIMESTAMP(s->exit_timestamp.realtime),
9fb86720
LP
6067 prefix, sigchld_code_to_string(s->code),
6068 prefix, s->status);
5cb5a6ff 6069}
44d8db9e 6070
34cf6c43 6071static void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
e1d75803 6072 _cleanup_free_ char *cmd = NULL;
4c940960 6073 const char *prefix2;
44d8db9e
LP
6074
6075 assert(c);
6076 assert(f);
6077
4c940960 6078 prefix = strempty(prefix);
63c372cb 6079 prefix2 = strjoina(prefix, "\t");
44d8db9e 6080
8a62620e 6081 cmd = quote_command_line(c->argv);
44d8db9e
LP
6082 fprintf(f,
6083 "%sCommand Line: %s\n",
4bbccb02 6084 prefix, cmd ? cmd : strerror_safe(ENOMEM));
44d8db9e 6085
9fb86720 6086 exec_status_dump(&c->exec_status, f, prefix2);
44d8db9e
LP
6087}
6088
6089void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
6090 assert(f);
6091
4c940960 6092 prefix = strempty(prefix);
44d8db9e
LP
6093
6094 LIST_FOREACH(command, c, c)
6095 exec_command_dump(c, f, prefix);
6096}
94f04347 6097
a6a80b4f
LP
6098void exec_command_append_list(ExecCommand **l, ExecCommand *e) {
6099 ExecCommand *end;
6100
6101 assert(l);
6102 assert(e);
6103
6104 if (*l) {
35b8ca3a 6105 /* It's kind of important, that we keep the order here */
71fda00f
LP
6106 LIST_FIND_TAIL(command, *l, end);
6107 LIST_INSERT_AFTER(command, *l, end, e);
a6a80b4f
LP
6108 } else
6109 *l = e;
6110}
6111
26fd040d
LP
6112int exec_command_set(ExecCommand *c, const char *path, ...) {
6113 va_list ap;
6114 char **l, *p;
6115
6116 assert(c);
6117 assert(path);
6118
6119 va_start(ap, path);
6120 l = strv_new_ap(path, ap);
6121 va_end(ap);
6122
6123 if (!l)
6124 return -ENOMEM;
6125
250a918d
LP
6126 p = strdup(path);
6127 if (!p) {
26fd040d
LP
6128 strv_free(l);
6129 return -ENOMEM;
6130 }
6131
6897dfe8 6132 free_and_replace(c->path, p);
26fd040d 6133
130d3d22 6134 return strv_free_and_replace(c->argv, l);
26fd040d
LP
6135}
6136
86b23b07 6137int exec_command_append(ExecCommand *c, const char *path, ...) {
e63ff941 6138 _cleanup_strv_free_ char **l = NULL;
86b23b07 6139 va_list ap;
86b23b07
JS
6140 int r;
6141
6142 assert(c);
6143 assert(path);
6144
6145 va_start(ap, path);
6146 l = strv_new_ap(path, ap);
6147 va_end(ap);
6148
6149 if (!l)
6150 return -ENOMEM;
6151
e287086b 6152 r = strv_extend_strv(&c->argv, l, false);
e63ff941 6153 if (r < 0)
86b23b07 6154 return r;
86b23b07
JS
6155
6156 return 0;
6157}
6158
e8a565cb
YW
6159static void *remove_tmpdir_thread(void *p) {
6160 _cleanup_free_ char *path = p;
86b23b07 6161
e8a565cb
YW
6162 (void) rm_rf(path, REMOVE_ROOT|REMOVE_PHYSICAL);
6163 return NULL;
6164}
6165
6166static ExecRuntime* exec_runtime_free(ExecRuntime *rt, bool destroy) {
6167 int r;
6168
6169 if (!rt)
6170 return NULL;
6171
6172 if (rt->manager)
6173 (void) hashmap_remove(rt->manager->exec_runtime_by_id, rt->id);
6174
6175 /* When destroy is true, then rm_rf tmp_dir and var_tmp_dir. */
56a13a49
ZJS
6176
6177 if (destroy && rt->tmp_dir && !streq(rt->tmp_dir, RUN_SYSTEMD_EMPTY)) {
e8a565cb
YW
6178 log_debug("Spawning thread to nuke %s", rt->tmp_dir);
6179
6180 r = asynchronous_job(remove_tmpdir_thread, rt->tmp_dir);
56a13a49 6181 if (r < 0)
e8a565cb 6182 log_warning_errno(r, "Failed to nuke %s: %m", rt->tmp_dir);
56a13a49
ZJS
6183 else
6184 rt->tmp_dir = NULL;
e8a565cb 6185 }
613b411c 6186
56a13a49 6187 if (destroy && rt->var_tmp_dir && !streq(rt->var_tmp_dir, RUN_SYSTEMD_EMPTY)) {
e8a565cb
YW
6188 log_debug("Spawning thread to nuke %s", rt->var_tmp_dir);
6189
6190 r = asynchronous_job(remove_tmpdir_thread, rt->var_tmp_dir);
56a13a49 6191 if (r < 0)
e8a565cb 6192 log_warning_errno(r, "Failed to nuke %s: %m", rt->var_tmp_dir);
56a13a49
ZJS
6193 else
6194 rt->var_tmp_dir = NULL;
e8a565cb
YW
6195 }
6196
6197 rt->id = mfree(rt->id);
6198 rt->tmp_dir = mfree(rt->tmp_dir);
6199 rt->var_tmp_dir = mfree(rt->var_tmp_dir);
6200 safe_close_pair(rt->netns_storage_socket);
a70581ff 6201 safe_close_pair(rt->ipcns_storage_socket);
e8a565cb
YW
6202 return mfree(rt);
6203}
6204
6205static void exec_runtime_freep(ExecRuntime **rt) {
da6bc6ed 6206 (void) exec_runtime_free(*rt, false);
e8a565cb
YW
6207}
6208
56a13a49
ZJS
6209static int exec_runtime_allocate(ExecRuntime **ret, const char *id) {
6210 _cleanup_free_ char *id_copy = NULL;
8e8009dc 6211 ExecRuntime *n;
613b411c 6212
8e8009dc 6213 assert(ret);
613b411c 6214
56a13a49
ZJS
6215 id_copy = strdup(id);
6216 if (!id_copy)
6217 return -ENOMEM;
6218
8e8009dc
LP
6219 n = new(ExecRuntime, 1);
6220 if (!n)
613b411c
LP
6221 return -ENOMEM;
6222
8e8009dc 6223 *n = (ExecRuntime) {
56a13a49 6224 .id = TAKE_PTR(id_copy),
8e8009dc 6225 .netns_storage_socket = { -1, -1 },
a70581ff 6226 .ipcns_storage_socket = { -1, -1 },
8e8009dc
LP
6227 };
6228
6229 *ret = n;
613b411c
LP
6230 return 0;
6231}
6232
e8a565cb
YW
6233static int exec_runtime_add(
6234 Manager *m,
6235 const char *id,
56a13a49
ZJS
6236 char **tmp_dir,
6237 char **var_tmp_dir,
6238 int netns_storage_socket[2],
a70581ff 6239 int ipcns_storage_socket[2],
e8a565cb
YW
6240 ExecRuntime **ret) {
6241
6242 _cleanup_(exec_runtime_freep) ExecRuntime *rt = NULL;
613b411c
LP
6243 int r;
6244
e8a565cb 6245 assert(m);
613b411c
LP
6246 assert(id);
6247
a70581ff 6248 /* tmp_dir, var_tmp_dir, {net,ipc}ns_storage_socket fds are donated on success */
56a13a49 6249
56a13a49 6250 r = exec_runtime_allocate(&rt, id);
613b411c
LP
6251 if (r < 0)
6252 return r;
6253
63083706 6254 r = hashmap_ensure_put(&m->exec_runtime_by_id, &string_hash_ops, rt->id, rt);
56a13a49
ZJS
6255 if (r < 0)
6256 return r;
e8a565cb 6257
56a13a49
ZJS
6258 assert(!!rt->tmp_dir == !!rt->var_tmp_dir); /* We require both to be set together */
6259 rt->tmp_dir = TAKE_PTR(*tmp_dir);
6260 rt->var_tmp_dir = TAKE_PTR(*var_tmp_dir);
e8a565cb
YW
6261
6262 if (netns_storage_socket) {
56a13a49
ZJS
6263 rt->netns_storage_socket[0] = TAKE_FD(netns_storage_socket[0]);
6264 rt->netns_storage_socket[1] = TAKE_FD(netns_storage_socket[1]);
613b411c
LP
6265 }
6266
a70581ff
XR
6267 if (ipcns_storage_socket) {
6268 rt->ipcns_storage_socket[0] = TAKE_FD(ipcns_storage_socket[0]);
6269 rt->ipcns_storage_socket[1] = TAKE_FD(ipcns_storage_socket[1]);
6270 }
6271
e8a565cb
YW
6272 rt->manager = m;
6273
6274 if (ret)
6275 *ret = rt;
e8a565cb 6276 /* do not remove created ExecRuntime object when the operation succeeds. */
56a13a49 6277 TAKE_PTR(rt);
e8a565cb
YW
6278 return 0;
6279}
6280
74aaf59b
LP
6281static int exec_runtime_make(
6282 Manager *m,
6283 const ExecContext *c,
6284 const char *id,
6285 ExecRuntime **ret) {
6286
56a13a49 6287 _cleanup_(namespace_cleanup_tmpdirp) char *tmp_dir = NULL, *var_tmp_dir = NULL;
a70581ff 6288 _cleanup_close_pair_ int netns_storage_socket[2] = { -1, -1 }, ipcns_storage_socket[2] = { -1, -1 };
e8a565cb
YW
6289 int r;
6290
6291 assert(m);
6292 assert(c);
6293 assert(id);
6294
6295 /* It is not necessary to create ExecRuntime object. */
a70581ff 6296 if (!c->private_network && !c->private_ipc && !c->private_tmp && !c->network_namespace_path) {
74aaf59b 6297 *ret = NULL;
e8a565cb 6298 return 0;
74aaf59b 6299 }
e8a565cb 6300
efa2f3a1
TM
6301 if (c->private_tmp &&
6302 !(prefixed_path_strv_contains(c->inaccessible_paths, "/tmp") &&
6303 (prefixed_path_strv_contains(c->inaccessible_paths, "/var/tmp") ||
6304 prefixed_path_strv_contains(c->inaccessible_paths, "/var")))) {
e8a565cb 6305 r = setup_tmp_dirs(id, &tmp_dir, &var_tmp_dir);
613b411c
LP
6306 if (r < 0)
6307 return r;
6308 }
6309
a8d08f39 6310 if (c->private_network || c->network_namespace_path) {
e8a565cb
YW
6311 if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, netns_storage_socket) < 0)
6312 return -errno;
6313 }
6314
a70581ff
XR
6315 if (c->private_ipc || c->ipc_namespace_path) {
6316 if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, ipcns_storage_socket) < 0)
6317 return -errno;
6318 }
6319
6320 r = exec_runtime_add(m, id, &tmp_dir, &var_tmp_dir, netns_storage_socket, ipcns_storage_socket, ret);
e8a565cb
YW
6321 if (r < 0)
6322 return r;
6323
613b411c
LP
6324 return 1;
6325}
6326
e8a565cb
YW
6327int exec_runtime_acquire(Manager *m, const ExecContext *c, const char *id, bool create, ExecRuntime **ret) {
6328 ExecRuntime *rt;
6329 int r;
613b411c 6330
e8a565cb
YW
6331 assert(m);
6332 assert(id);
6333 assert(ret);
6334
6335 rt = hashmap_get(m->exec_runtime_by_id, id);
6336 if (rt)
387f6955 6337 /* We already have an ExecRuntime object, let's increase the ref count and reuse it */
e8a565cb
YW
6338 goto ref;
6339
74aaf59b
LP
6340 if (!create) {
6341 *ret = NULL;
e8a565cb 6342 return 0;
74aaf59b 6343 }
e8a565cb
YW
6344
6345 /* If not found, then create a new object. */
6346 r = exec_runtime_make(m, c, id, &rt);
74aaf59b 6347 if (r < 0)
e8a565cb 6348 return r;
74aaf59b
LP
6349 if (r == 0) {
6350 /* When r == 0, it is not necessary to create ExecRuntime object. */
6351 *ret = NULL;
6352 return 0;
6353 }
613b411c 6354
e8a565cb
YW
6355ref:
6356 /* increment reference counter. */
6357 rt->n_ref++;
6358 *ret = rt;
6359 return 1;
6360}
613b411c 6361
e8a565cb
YW
6362ExecRuntime *exec_runtime_unref(ExecRuntime *rt, bool destroy) {
6363 if (!rt)
613b411c
LP
6364 return NULL;
6365
e8a565cb 6366 assert(rt->n_ref > 0);
613b411c 6367
e8a565cb
YW
6368 rt->n_ref--;
6369 if (rt->n_ref > 0)
f2341e0a
LP
6370 return NULL;
6371
e8a565cb 6372 return exec_runtime_free(rt, destroy);
613b411c
LP
6373}
6374
e8a565cb
YW
6375int exec_runtime_serialize(const Manager *m, FILE *f, FDSet *fds) {
6376 ExecRuntime *rt;
e8a565cb
YW
6377
6378 assert(m);
613b411c
LP
6379 assert(f);
6380 assert(fds);
6381
90e74a66 6382 HASHMAP_FOREACH(rt, m->exec_runtime_by_id) {
e8a565cb 6383 fprintf(f, "exec-runtime=%s", rt->id);
613b411c 6384
e8a565cb
YW
6385 if (rt->tmp_dir)
6386 fprintf(f, " tmp-dir=%s", rt->tmp_dir);
613b411c 6387
e8a565cb
YW
6388 if (rt->var_tmp_dir)
6389 fprintf(f, " var-tmp-dir=%s", rt->var_tmp_dir);
613b411c 6390
e8a565cb
YW
6391 if (rt->netns_storage_socket[0] >= 0) {
6392 int copy;
613b411c 6393
e8a565cb
YW
6394 copy = fdset_put_dup(fds, rt->netns_storage_socket[0]);
6395 if (copy < 0)
6396 return copy;
613b411c 6397
e8a565cb
YW
6398 fprintf(f, " netns-socket-0=%i", copy);
6399 }
613b411c 6400
e8a565cb
YW
6401 if (rt->netns_storage_socket[1] >= 0) {
6402 int copy;
613b411c 6403
e8a565cb
YW
6404 copy = fdset_put_dup(fds, rt->netns_storage_socket[1]);
6405 if (copy < 0)
6406 return copy;
613b411c 6407
e8a565cb
YW
6408 fprintf(f, " netns-socket-1=%i", copy);
6409 }
6410
a70581ff
XR
6411 if (rt->ipcns_storage_socket[0] >= 0) {
6412 int copy;
6413
6414 copy = fdset_put_dup(fds, rt->ipcns_storage_socket[0]);
6415 if (copy < 0)
6416 return copy;
6417
6418 fprintf(f, " ipcns-socket-0=%i", copy);
6419 }
6420
6421 if (rt->ipcns_storage_socket[1] >= 0) {
6422 int copy;
6423
6424 copy = fdset_put_dup(fds, rt->ipcns_storage_socket[1]);
6425 if (copy < 0)
6426 return copy;
6427
6428 fprintf(f, " ipcns-socket-1=%i", copy);
6429 }
6430
e8a565cb 6431 fputc('\n', f);
613b411c
LP
6432 }
6433
6434 return 0;
6435}
6436
e8a565cb
YW
6437int exec_runtime_deserialize_compat(Unit *u, const char *key, const char *value, FDSet *fds) {
6438 _cleanup_(exec_runtime_freep) ExecRuntime *rt_create = NULL;
6439 ExecRuntime *rt;
613b411c
LP
6440 int r;
6441
e8a565cb
YW
6442 /* This is for the migration from old (v237 or earlier) deserialization text.
6443 * Due to the bug #7790, this may not work with the units that use JoinsNamespaceOf=.
6444 * Even if the ExecRuntime object originally created by the other unit, we cannot judge
6445 * so or not from the serialized text, then we always creates a new object owned by this. */
6446
6447 assert(u);
613b411c
LP
6448 assert(key);
6449 assert(value);
6450
e8a565cb
YW
6451 /* Manager manages ExecRuntime objects by the unit id.
6452 * So, we omit the serialized text when the unit does not have id (yet?)... */
6453 if (isempty(u->id)) {
6454 log_unit_debug(u, "Invocation ID not found. Dropping runtime parameter.");
6455 return 0;
6456 }
613b411c 6457
cbc165d1
ZJS
6458 if (hashmap_ensure_allocated(&u->manager->exec_runtime_by_id, &string_hash_ops) < 0)
6459 return log_oom();
e8a565cb
YW
6460
6461 rt = hashmap_get(u->manager->exec_runtime_by_id, u->id);
6462 if (!rt) {
cbc165d1 6463 if (exec_runtime_allocate(&rt_create, u->id) < 0)
f2341e0a 6464 return log_oom();
613b411c 6465
e8a565cb
YW
6466 rt = rt_create;
6467 }
6468
6469 if (streq(key, "tmp-dir")) {
cbc165d1
ZJS
6470 if (free_and_strdup_warn(&rt->tmp_dir, value) < 0)
6471 return -ENOMEM;
613b411c
LP
6472
6473 } else if (streq(key, "var-tmp-dir")) {
cbc165d1
ZJS
6474 if (free_and_strdup_warn(&rt->var_tmp_dir, value) < 0)
6475 return -ENOMEM;
613b411c
LP
6476
6477 } else if (streq(key, "netns-socket-0")) {
6478 int fd;
6479
e8a565cb 6480 if (safe_atoi(value, &fd) < 0 || !fdset_contains(fds, fd)) {
f2341e0a 6481 log_unit_debug(u, "Failed to parse netns socket value: %s", value);
e8a565cb 6482 return 0;
613b411c 6483 }
e8a565cb
YW
6484
6485 safe_close(rt->netns_storage_socket[0]);
6486 rt->netns_storage_socket[0] = fdset_remove(fds, fd);
6487
613b411c
LP
6488 } else if (streq(key, "netns-socket-1")) {
6489 int fd;
6490
e8a565cb 6491 if (safe_atoi(value, &fd) < 0 || !fdset_contains(fds, fd)) {
f2341e0a 6492 log_unit_debug(u, "Failed to parse netns socket value: %s", value);
e8a565cb 6493 return 0;
613b411c 6494 }
e8a565cb
YW
6495
6496 safe_close(rt->netns_storage_socket[1]);
6497 rt->netns_storage_socket[1] = fdset_remove(fds, fd);
a70581ff 6498
613b411c
LP
6499 } else
6500 return 0;
6501
e8a565cb
YW
6502 /* If the object is newly created, then put it to the hashmap which manages ExecRuntime objects. */
6503 if (rt_create) {
6504 r = hashmap_put(u->manager->exec_runtime_by_id, rt_create->id, rt_create);
6505 if (r < 0) {
3fe91079 6506 log_unit_debug_errno(u, r, "Failed to put runtime parameter to manager's storage: %m");
e8a565cb
YW
6507 return 0;
6508 }
613b411c 6509
e8a565cb 6510 rt_create->manager = u->manager;
613b411c 6511
e8a565cb 6512 /* Avoid cleanup */
56a13a49 6513 TAKE_PTR(rt_create);
e8a565cb 6514 }
98b47d54 6515
e8a565cb
YW
6516 return 1;
6517}
613b411c 6518
56a13a49
ZJS
6519int exec_runtime_deserialize_one(Manager *m, const char *value, FDSet *fds) {
6520 _cleanup_free_ char *tmp_dir = NULL, *var_tmp_dir = NULL;
6521 char *id = NULL;
a70581ff 6522 int r, netns_fdpair[] = {-1, -1}, ipcns_fdpair[] = {-1, -1};
e8a565cb
YW
6523 const char *p, *v = value;
6524 size_t n;
613b411c 6525
e8a565cb
YW
6526 assert(m);
6527 assert(value);
6528 assert(fds);
98b47d54 6529
e8a565cb 6530 n = strcspn(v, " ");
2f82562b 6531 id = strndupa_safe(v, n);
e8a565cb
YW
6532 if (v[n] != ' ')
6533 goto finalize;
6534 p = v + n + 1;
6535
6536 v = startswith(p, "tmp-dir=");
6537 if (v) {
6538 n = strcspn(v, " ");
56a13a49
ZJS
6539 tmp_dir = strndup(v, n);
6540 if (!tmp_dir)
6541 return log_oom();
e8a565cb
YW
6542 if (v[n] != ' ')
6543 goto finalize;
6544 p = v + n + 1;
6545 }
6546
6547 v = startswith(p, "var-tmp-dir=");
6548 if (v) {
6549 n = strcspn(v, " ");
56a13a49
ZJS
6550 var_tmp_dir = strndup(v, n);
6551 if (!var_tmp_dir)
6552 return log_oom();
e8a565cb
YW
6553 if (v[n] != ' ')
6554 goto finalize;
6555 p = v + n + 1;
6556 }
6557
6558 v = startswith(p, "netns-socket-0=");
6559 if (v) {
6560 char *buf;
6561
6562 n = strcspn(v, " ");
2f82562b 6563 buf = strndupa_safe(v, n);
c413bb28 6564
a70581ff 6565 r = safe_atoi(buf, &netns_fdpair[0]);
c413bb28
ZJS
6566 if (r < 0)
6567 return log_debug_errno(r, "Unable to parse exec-runtime specification netns-socket-0=%s: %m", buf);
a70581ff 6568 if (!fdset_contains(fds, netns_fdpair[0]))
c413bb28 6569 return log_debug_errno(SYNTHETIC_ERRNO(EBADF),
a70581ff
XR
6570 "exec-runtime specification netns-socket-0= refers to unknown fd %d: %m", netns_fdpair[0]);
6571 netns_fdpair[0] = fdset_remove(fds, netns_fdpair[0]);
e8a565cb
YW
6572 if (v[n] != ' ')
6573 goto finalize;
6574 p = v + n + 1;
613b411c
LP
6575 }
6576
e8a565cb
YW
6577 v = startswith(p, "netns-socket-1=");
6578 if (v) {
6579 char *buf;
98b47d54 6580
e8a565cb 6581 n = strcspn(v, " ");
2f82562b 6582 buf = strndupa_safe(v, n);
a70581ff
XR
6583
6584 r = safe_atoi(buf, &netns_fdpair[1]);
c413bb28
ZJS
6585 if (r < 0)
6586 return log_debug_errno(r, "Unable to parse exec-runtime specification netns-socket-1=%s: %m", buf);
a70581ff
XR
6587 if (!fdset_contains(fds, netns_fdpair[1]))
6588 return log_debug_errno(SYNTHETIC_ERRNO(EBADF),
6589 "exec-runtime specification netns-socket-1= refers to unknown fd %d: %m", netns_fdpair[1]);
6590 netns_fdpair[1] = fdset_remove(fds, netns_fdpair[1]);
6591 if (v[n] != ' ')
6592 goto finalize;
6593 p = v + n + 1;
6594 }
6595
6596 v = startswith(p, "ipcns-socket-0=");
6597 if (v) {
6598 char *buf;
6599
6600 n = strcspn(v, " ");
2f82562b 6601 buf = strndupa_safe(v, n);
a70581ff
XR
6602
6603 r = safe_atoi(buf, &ipcns_fdpair[0]);
6604 if (r < 0)
6605 return log_debug_errno(r, "Unable to parse exec-runtime specification ipcns-socket-0=%s: %m", buf);
6606 if (!fdset_contains(fds, ipcns_fdpair[0]))
6607 return log_debug_errno(SYNTHETIC_ERRNO(EBADF),
6608 "exec-runtime specification ipcns-socket-0= refers to unknown fd %d: %m", ipcns_fdpair[0]);
6609 ipcns_fdpair[0] = fdset_remove(fds, ipcns_fdpair[0]);
6610 if (v[n] != ' ')
6611 goto finalize;
6612 p = v + n + 1;
6613 }
6614
6615 v = startswith(p, "ipcns-socket-1=");
6616 if (v) {
6617 char *buf;
6618
6619 n = strcspn(v, " ");
2f82562b 6620 buf = strndupa_safe(v, n);
a70581ff
XR
6621
6622 r = safe_atoi(buf, &ipcns_fdpair[1]);
6623 if (r < 0)
6624 return log_debug_errno(r, "Unable to parse exec-runtime specification ipcns-socket-1=%s: %m", buf);
6625 if (!fdset_contains(fds, ipcns_fdpair[1]))
c413bb28 6626 return log_debug_errno(SYNTHETIC_ERRNO(EBADF),
a70581ff
XR
6627 "exec-runtime specification ipcns-socket-1= refers to unknown fd %d: %m", ipcns_fdpair[1]);
6628 ipcns_fdpair[1] = fdset_remove(fds, ipcns_fdpair[1]);
e8a565cb 6629 }
98b47d54 6630
e8a565cb 6631finalize:
a70581ff 6632 r = exec_runtime_add(m, id, &tmp_dir, &var_tmp_dir, netns_fdpair, ipcns_fdpair, NULL);
7d853ca6 6633 if (r < 0)
56a13a49
ZJS
6634 return log_debug_errno(r, "Failed to add exec-runtime: %m");
6635 return 0;
e8a565cb 6636}
613b411c 6637
e8a565cb
YW
6638void exec_runtime_vacuum(Manager *m) {
6639 ExecRuntime *rt;
e8a565cb
YW
6640
6641 assert(m);
6642
6643 /* Free unreferenced ExecRuntime objects. This is used after manager deserialization process. */
6644
90e74a66 6645 HASHMAP_FOREACH(rt, m->exec_runtime_by_id) {
e8a565cb
YW
6646 if (rt->n_ref > 0)
6647 continue;
6648
6649 (void) exec_runtime_free(rt, false);
6650 }
613b411c
LP
6651}
6652
b9c04eaf
YW
6653void exec_params_clear(ExecParameters *p) {
6654 if (!p)
6655 return;
6656
c3f8a065
LP
6657 p->environment = strv_free(p->environment);
6658 p->fd_names = strv_free(p->fd_names);
6659 p->fds = mfree(p->fds);
6660 p->exec_fd = safe_close(p->exec_fd);
b9c04eaf
YW
6661}
6662
bb0c0d6f
LP
6663ExecSetCredential *exec_set_credential_free(ExecSetCredential *sc) {
6664 if (!sc)
6665 return NULL;
6666
6667 free(sc->id);
6668 free(sc->data);
6669 return mfree(sc);
6670}
6671
43144be4
LP
6672ExecLoadCredential *exec_load_credential_free(ExecLoadCredential *lc) {
6673 if (!lc)
6674 return NULL;
6675
6676 free(lc->id);
6677 free(lc->path);
6678 return mfree(lc);
6679}
6680
bb0c0d6f 6681DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(exec_set_credential_hash_ops, char, string_hash_func, string_compare_func, ExecSetCredential, exec_set_credential_free);
43144be4 6682DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(exec_load_credential_hash_ops, char, string_hash_func, string_compare_func, ExecLoadCredential, exec_load_credential_free);
bb0c0d6f 6683
80876c20
LP
6684static const char* const exec_input_table[_EXEC_INPUT_MAX] = {
6685 [EXEC_INPUT_NULL] = "null",
6686 [EXEC_INPUT_TTY] = "tty",
6687 [EXEC_INPUT_TTY_FORCE] = "tty-force",
4f2d528d 6688 [EXEC_INPUT_TTY_FAIL] = "tty-fail",
52c239d7
LB
6689 [EXEC_INPUT_SOCKET] = "socket",
6690 [EXEC_INPUT_NAMED_FD] = "fd",
08f3be7a 6691 [EXEC_INPUT_DATA] = "data",
2038c3f5 6692 [EXEC_INPUT_FILE] = "file",
80876c20
LP
6693};
6694
8a0867d6
LP
6695DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput);
6696
94f04347 6697static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = {
80876c20 6698 [EXEC_OUTPUT_INHERIT] = "inherit",
94f04347 6699 [EXEC_OUTPUT_NULL] = "null",
80876c20 6700 [EXEC_OUTPUT_TTY] = "tty",
9a6bca7a 6701 [EXEC_OUTPUT_KMSG] = "kmsg",
28dbc1e8 6702 [EXEC_OUTPUT_KMSG_AND_CONSOLE] = "kmsg+console",
706343f4
LP
6703 [EXEC_OUTPUT_JOURNAL] = "journal",
6704 [EXEC_OUTPUT_JOURNAL_AND_CONSOLE] = "journal+console",
52c239d7
LB
6705 [EXEC_OUTPUT_SOCKET] = "socket",
6706 [EXEC_OUTPUT_NAMED_FD] = "fd",
2038c3f5 6707 [EXEC_OUTPUT_FILE] = "file",
566b7d23 6708 [EXEC_OUTPUT_FILE_APPEND] = "append",
8d7dab1f 6709 [EXEC_OUTPUT_FILE_TRUNCATE] = "truncate",
94f04347
LP
6710};
6711
6712DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput);
023a4f67
LP
6713
6714static const char* const exec_utmp_mode_table[_EXEC_UTMP_MODE_MAX] = {
6715 [EXEC_UTMP_INIT] = "init",
6716 [EXEC_UTMP_LOGIN] = "login",
6717 [EXEC_UTMP_USER] = "user",
6718};
6719
6720DEFINE_STRING_TABLE_LOOKUP(exec_utmp_mode, ExecUtmpMode);
53f47dfc
YW
6721
6722static const char* const exec_preserve_mode_table[_EXEC_PRESERVE_MODE_MAX] = {
6723 [EXEC_PRESERVE_NO] = "no",
6724 [EXEC_PRESERVE_YES] = "yes",
6725 [EXEC_PRESERVE_RESTART] = "restart",
6726};
6727
6728DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(exec_preserve_mode, ExecPreserveMode, EXEC_PRESERVE_YES);
3536f49e 6729
6b7b2ed9 6730/* This table maps ExecDirectoryType to the setting it is configured with in the unit */
72fd1768 6731static const char* const exec_directory_type_table[_EXEC_DIRECTORY_TYPE_MAX] = {
3536f49e
YW
6732 [EXEC_DIRECTORY_RUNTIME] = "RuntimeDirectory",
6733 [EXEC_DIRECTORY_STATE] = "StateDirectory",
6734 [EXEC_DIRECTORY_CACHE] = "CacheDirectory",
6735 [EXEC_DIRECTORY_LOGS] = "LogsDirectory",
6736 [EXEC_DIRECTORY_CONFIGURATION] = "ConfigurationDirectory",
6737};
6738
6739DEFINE_STRING_TABLE_LOOKUP(exec_directory_type, ExecDirectoryType);
b1edf445 6740
6b7b2ed9
LP
6741/* And this table maps ExecDirectoryType too, but to a generic term identifying the type of resource. This
6742 * one is supposed to be generic enough to be used for unit types that don't use ExecContext and per-unit
6743 * directories, specifically .timer units with their timestamp touch file. */
6744static const char* const exec_resource_type_table[_EXEC_DIRECTORY_TYPE_MAX] = {
6745 [EXEC_DIRECTORY_RUNTIME] = "runtime",
6746 [EXEC_DIRECTORY_STATE] = "state",
6747 [EXEC_DIRECTORY_CACHE] = "cache",
6748 [EXEC_DIRECTORY_LOGS] = "logs",
6749 [EXEC_DIRECTORY_CONFIGURATION] = "configuration",
6750};
6751
6752DEFINE_STRING_TABLE_LOOKUP(exec_resource_type, ExecDirectoryType);
6753
6754/* And this table also maps ExecDirectoryType, to the environment variable we pass the selected directory to
6755 * the service payload in. */
fb2042dd
YW
6756static const char* const exec_directory_env_name_table[_EXEC_DIRECTORY_TYPE_MAX] = {
6757 [EXEC_DIRECTORY_RUNTIME] = "RUNTIME_DIRECTORY",
6758 [EXEC_DIRECTORY_STATE] = "STATE_DIRECTORY",
6759 [EXEC_DIRECTORY_CACHE] = "CACHE_DIRECTORY",
6760 [EXEC_DIRECTORY_LOGS] = "LOGS_DIRECTORY",
6761 [EXEC_DIRECTORY_CONFIGURATION] = "CONFIGURATION_DIRECTORY",
6762};
6763
6764DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(exec_directory_env_name, ExecDirectoryType);
6765
b1edf445
LP
6766static const char* const exec_keyring_mode_table[_EXEC_KEYRING_MODE_MAX] = {
6767 [EXEC_KEYRING_INHERIT] = "inherit",
6768 [EXEC_KEYRING_PRIVATE] = "private",
6769 [EXEC_KEYRING_SHARED] = "shared",
6770};
6771
6772DEFINE_STRING_TABLE_LOOKUP(exec_keyring_mode, ExecKeyringMode);