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