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