]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/execute.c
tree-wide: use UINT64_MAX or friends
[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 */
1433 return context_has_address_families(c) ||
1434 c->memory_deny_write_execute ||
1435 c->restrict_realtime ||
f69567cb 1436 c->restrict_suid_sgid ||
469830d1 1437 exec_context_restrict_namespaces_set(c) ||
fc64760d 1438 c->protect_clock ||
469830d1
LP
1439 c->protect_kernel_tunables ||
1440 c->protect_kernel_modules ||
84703040 1441 c->protect_kernel_logs ||
469830d1
LP
1442 c->private_devices ||
1443 context_has_syscall_filters(c) ||
9df2cdd8 1444 context_has_syscall_logs(c) ||
78e864e5 1445 !set_isempty(c->syscall_archs) ||
aecd5ac6
TM
1446 c->lock_personality ||
1447 c->protect_hostname;
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;
bb0c0d6f
LP
2567 const char *source;
2568 size_t size, add;
2569
2570 if (path_is_absolute(*fn)) {
2571 /* If this is an absolute path, read the data directly from it, and support AF_UNIX sockets */
2572 source = *fn;
2573 flags |= READ_FULL_FILE_CONNECT_SOCKET;
d3dcf4e3
LP
2574
2575 /* Pass some minimal info about the unit and the credential name we are looking to acquire
2576 * via the source socket address in case we read off an AF_UNIX socket. */
2577 if (asprintf(&bindname, "@%" PRIx64"/unit/%s/%s", random_u64(), unit, *id) < 0)
2578 return -ENOMEM;
2579
bb0c0d6f
LP
2580 } else if (params->received_credentials) {
2581 /* If this is a relative path, take it relative to the credentials we received
2582 * ourselves. We don't support the AF_UNIX stuff in this mode, since we are operating
2583 * on a credential store, i.e. this is guaranteed to be regular files. */
2584 j = path_join(params->received_credentials, *fn);
2585 if (!j)
2586 return -ENOMEM;
2587
2588 source = j;
2589 } else
2590 source = NULL;
2591
d3dcf4e3 2592
bb0c0d6f 2593 if (source)
986311c2 2594 r = read_full_file_full(AT_FDCWD, source, UINT64_MAX, SIZE_MAX, flags, bindname, &data, &size);
bb0c0d6f
LP
2595 else
2596 r = -ENOENT;
2597 if (r == -ENOENT &&
2598 faccessat(dfd, *id, F_OK, AT_SYMLINK_NOFOLLOW) >= 0) /* If the source file doesn't exist, but we already acquired the key otherwise, then don't fail */
2599 continue;
2600 if (r < 0)
2601 return r;
2602
2603 add = strlen(*id) + size;
2604 if (add > left)
2605 return -E2BIG;
2606
2607 r = write_credential(dfd, *id, data, size, uid, ownership_ok);
2608 if (r < 0)
2609 return r;
2610
2611 left -= add;
2612 }
2613
2614 if (fchmod(dfd, 0500) < 0) /* Now take away the "w" bit */
2615 return -errno;
2616
2617 /* After we created all keys with the right perms, also make sure the credential store as a whole is
2618 * accessible */
2619
2620 if (uid_is_valid(uid) && uid != getuid()) {
567aeb58 2621 r = fd_add_uid_acl_permission(dfd, uid, ACL_READ | ACL_EXECUTE);
bb0c0d6f
LP
2622 if (r < 0) {
2623 if (!ERRNO_IS_NOT_SUPPORTED(r) && !ERRNO_IS_PRIVILEGE(r))
2624 return r;
2625
2626 if (!ownership_ok)
2627 return r;
2628
f5fbe71d 2629 if (fchown(dfd, uid, GID_INVALID) < 0)
bb0c0d6f
LP
2630 return -errno;
2631 }
2632 }
2633
2634 return 0;
2635}
2636
2637static int setup_credentials_internal(
2638 const ExecContext *context,
2639 const ExecParameters *params,
d3dcf4e3 2640 const char *unit,
bb0c0d6f
LP
2641 const char *final, /* This is where the credential store shall eventually end up at */
2642 const char *workspace, /* This is where we can prepare it before moving it to the final place */
2643 bool reuse_workspace, /* Whether to reuse any existing workspace mount if it already is a mount */
2644 bool must_mount, /* Whether to require that we mount something, it's not OK to use the plain directory fall back */
2645 uid_t uid) {
2646
2647 int r, workspace_mounted; /* negative if we don't know yet whether we have/can mount something; true
2648 * if we mounted something; false if we definitely can't mount anything */
2649 bool final_mounted;
2650 const char *where;
2651
2652 assert(context);
2653 assert(final);
2654 assert(workspace);
2655
2656 if (reuse_workspace) {
2657 r = path_is_mount_point(workspace, NULL, 0);
2658 if (r < 0)
2659 return r;
2660 if (r > 0)
2661 workspace_mounted = true; /* If this is already a mount, and we are supposed to reuse it, let's keep this in mind */
2662 else
2663 workspace_mounted = -1; /* We need to figure out if we can mount something to the workspace */
2664 } else
2665 workspace_mounted = -1; /* ditto */
2666
2667 r = path_is_mount_point(final, NULL, 0);
2668 if (r < 0)
2669 return r;
2670 if (r > 0) {
2671 /* If the final place already has something mounted, we use that. If the workspace also has
2672 * something mounted we assume it's actually the same mount (but with MS_RDONLY
2673 * different). */
2674 final_mounted = true;
2675
2676 if (workspace_mounted < 0) {
2677 /* If the final place is mounted, but the workspace we isn't, then let's bind mount
2678 * the final version to the workspace, and make it writable, so that we can make
2679 * changes */
2680
21935150
LP
2681 r = mount_nofollow_verbose(LOG_DEBUG, final, workspace, NULL, MS_BIND|MS_REC, NULL);
2682 if (r < 0)
2683 return r;
bb0c0d6f 2684
21935150
LP
2685 r = mount_nofollow_verbose(LOG_DEBUG, NULL, workspace, NULL, MS_BIND|MS_REMOUNT|MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL);
2686 if (r < 0)
2687 return r;
bb0c0d6f
LP
2688
2689 workspace_mounted = true;
2690 }
2691 } else
2692 final_mounted = false;
2693
2694 if (workspace_mounted < 0) {
2695 /* Nothing is mounted on the workspace yet, let's try to mount something now */
2696 for (int try = 0;; try++) {
2697
2698 if (try == 0) {
2699 /* Try "ramfs" first, since it's not swap backed */
21935150
LP
2700 r = mount_nofollow_verbose(LOG_DEBUG, "ramfs", workspace, "ramfs", MS_NODEV|MS_NOEXEC|MS_NOSUID, "mode=0700");
2701 if (r >= 0) {
bb0c0d6f
LP
2702 workspace_mounted = true;
2703 break;
2704 }
2705
2706 } else if (try == 1) {
2707 _cleanup_free_ char *opts = NULL;
2708
2709 if (asprintf(&opts, "mode=0700,nr_inodes=1024,size=%lu", CREDENTIALS_BYTES_MAX) < 0)
2710 return -ENOMEM;
2711
2712 /* Fall back to "tmpfs" otherwise */
21935150
LP
2713 r = mount_nofollow_verbose(LOG_DEBUG, "tmpfs", workspace, "tmpfs", MS_NODEV|MS_NOEXEC|MS_NOSUID, opts);
2714 if (r >= 0) {
bb0c0d6f
LP
2715 workspace_mounted = true;
2716 break;
2717 }
2718
2719 } else {
2720 /* 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
2721 r = mount_nofollow_verbose(LOG_DEBUG, final, workspace, NULL, MS_BIND|MS_REC, NULL);
2722 if (r < 0) {
2723 if (!ERRNO_IS_PRIVILEGE(r)) /* Propagate anything that isn't a permission problem */
2724 return r;
bb0c0d6f
LP
2725
2726 if (must_mount) /* If we it's not OK to use the plain directory
2727 * fallback, propagate all errors too */
21935150 2728 return r;
bb0c0d6f
LP
2729
2730 /* If we lack privileges to bind mount stuff, then let's gracefully
2731 * proceed for compat with container envs, and just use the final dir
2732 * as is. */
2733
2734 workspace_mounted = false;
2735 break;
2736 }
2737
2738 /* Make the new bind mount writable (i.e. drop MS_RDONLY) */
21935150
LP
2739 r = mount_nofollow_verbose(LOG_DEBUG, NULL, workspace, NULL, MS_BIND|MS_REMOUNT|MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL);
2740 if (r < 0)
2741 return r;
bb0c0d6f
LP
2742
2743 workspace_mounted = true;
2744 break;
2745 }
2746 }
2747 }
2748
2749 assert(!must_mount || workspace_mounted > 0);
2750 where = workspace_mounted ? workspace : final;
2751
d3dcf4e3 2752 r = acquire_credentials(context, params, unit, where, uid, workspace_mounted);
bb0c0d6f
LP
2753 if (r < 0)
2754 return r;
2755
2756 if (workspace_mounted) {
2757 /* Make workspace read-only now, so that any bind mount we make from it defaults to read-only too */
21935150
LP
2758 r = mount_nofollow_verbose(LOG_DEBUG, NULL, workspace, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY|MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL);
2759 if (r < 0)
2760 return r;
bb0c0d6f
LP
2761
2762 /* And mount it to the final place, read-only */
21935150
LP
2763 if (final_mounted)
2764 r = umount_verbose(LOG_DEBUG, workspace, MNT_DETACH|UMOUNT_NOFOLLOW);
2765 else
2766 r = mount_nofollow_verbose(LOG_DEBUG, workspace, final, NULL, MS_MOVE, NULL);
2767 if (r < 0)
2768 return r;
bb0c0d6f
LP
2769 } else {
2770 _cleanup_free_ char *parent = NULL;
2771
2772 /* If we do not have our own mount put used the plain directory fallback, then we need to
2773 * open access to the top-level credential directory and the per-service directory now */
2774
2775 parent = dirname_malloc(final);
2776 if (!parent)
2777 return -ENOMEM;
2778 if (chmod(parent, 0755) < 0)
2779 return -errno;
2780 }
2781
2782 return 0;
2783}
2784
2785static int setup_credentials(
2786 const ExecContext *context,
2787 const ExecParameters *params,
2788 const char *unit,
2789 uid_t uid) {
2790
2791 _cleanup_free_ char *p = NULL, *q = NULL;
2792 const char *i;
2793 int r;
2794
2795 assert(context);
2796 assert(params);
2797
2798 if (!exec_context_has_credentials(context))
2799 return 0;
2800
2801 if (!params->prefix[EXEC_DIRECTORY_RUNTIME])
2802 return -EINVAL;
2803
2804 /* This where we'll place stuff when we are done; this main credentials directory is world-readable,
2805 * and the subdir we mount over with a read-only file system readable by the service's user */
2806 q = path_join(params->prefix[EXEC_DIRECTORY_RUNTIME], "credentials");
2807 if (!q)
2808 return -ENOMEM;
2809
2810 r = mkdir_label(q, 0755); /* top-level dir: world readable/searchable */
2811 if (r < 0 && r != -EEXIST)
2812 return r;
2813
2814 p = path_join(q, unit);
2815 if (!p)
2816 return -ENOMEM;
2817
2818 r = mkdir_label(p, 0700); /* per-unit dir: private to user */
2819 if (r < 0 && r != -EEXIST)
2820 return r;
2821
2822 r = safe_fork("(sd-mkdcreds)", FORK_DEATHSIG|FORK_WAIT|FORK_NEW_MOUNTNS, NULL);
2823 if (r < 0) {
2824 _cleanup_free_ char *t = NULL, *u = NULL;
2825
2826 /* If this is not a privilege or support issue then propagate the error */
2827 if (!ERRNO_IS_NOT_SUPPORTED(r) && !ERRNO_IS_PRIVILEGE(r))
2828 return r;
2829
2830 /* Temporary workspace, that remains inaccessible all the time. We prepare stuff there before moving
2831 * it into place, so that users can't access half-initialized credential stores. */
2832 t = path_join(params->prefix[EXEC_DIRECTORY_RUNTIME], "systemd/temporary-credentials");
2833 if (!t)
2834 return -ENOMEM;
2835
2836 /* We can't set up a mount namespace. In that case operate on a fixed, inaccessible per-unit
2837 * directory outside of /run/credentials/ first, and then move it over to /run/credentials/
2838 * after it is fully set up */
2839 u = path_join(t, unit);
2840 if (!u)
2841 return -ENOMEM;
2842
2843 FOREACH_STRING(i, t, u) {
2844 r = mkdir_label(i, 0700);
2845 if (r < 0 && r != -EEXIST)
2846 return r;
2847 }
2848
2849 r = setup_credentials_internal(
2850 context,
2851 params,
d3dcf4e3 2852 unit,
bb0c0d6f
LP
2853 p, /* final mount point */
2854 u, /* temporary workspace to overmount */
2855 true, /* reuse the workspace if it is already a mount */
2856 false, /* it's OK to fall back to a plain directory if we can't mount anything */
2857 uid);
2858
2859 (void) rmdir(u); /* remove the workspace again if we can. */
2860
2861 if (r < 0)
2862 return r;
2863
2864 } else if (r == 0) {
2865
2866 /* We managed to set up a mount namespace, and are now in a child. That's great. In this case
2867 * we can use the same directory for all cases, after turning off propagation. Question
2868 * though is: where do we turn off propagation exactly, and where do we place the workspace
2869 * directory? We need some place that is guaranteed to be a mount point in the host, and
2870 * which is guaranteed to have a subdir we can mount over. /run/ is not suitable for this,
2871 * since we ultimately want to move the resulting file system there, i.e. we need propagation
2872 * for /run/ eventually. We could use our own /run/systemd/bind mount on itself, but that
2873 * would be visible in the host mount table all the time, which we want to avoid. Hence, what
2874 * we do here instead we use /dev/ and /dev/shm/ for our purposes. We know for sure that
2875 * /dev/ is a mount point and we now for sure that /dev/shm/ exists. Hence we can turn off
2876 * propagation on the former, and then overmount the latter.
2877 *
2878 * Yes it's nasty playing games with /dev/ and /dev/shm/ like this, since it does not exist
2879 * for this purpose, but there are few other candidates that work equally well for us, and
2880 * given that the we do this in a privately namespaced short-lived single-threaded process
69e3234d 2881 * that no one else sees this should be OK to do.*/
bb0c0d6f 2882
21935150
LP
2883 r = mount_nofollow_verbose(LOG_DEBUG, NULL, "/dev", NULL, MS_SLAVE|MS_REC, NULL); /* Turn off propagation from our namespace to host */
2884 if (r < 0)
bb0c0d6f
LP
2885 goto child_fail;
2886
2887 r = setup_credentials_internal(
2888 context,
2889 params,
d3dcf4e3 2890 unit,
bb0c0d6f
LP
2891 p, /* final mount point */
2892 "/dev/shm", /* temporary workspace to overmount */
2893 false, /* do not reuse /dev/shm if it is already a mount, under no circumstances */
2894 true, /* insist that something is mounted, do not allow fallback to plain directory */
2895 uid);
2896 if (r < 0)
2897 goto child_fail;
2898
2899 _exit(EXIT_SUCCESS);
2900
2901 child_fail:
2902 _exit(EXIT_FAILURE);
2903 }
2904
2905 return 0;
2906}
2907
92b423b9 2908#if ENABLE_SMACK
cefc33ae
LP
2909static int setup_smack(
2910 const ExecContext *context,
b83d5050 2911 int executable_fd) {
cefc33ae
LP
2912 int r;
2913
2914 assert(context);
b83d5050 2915 assert(executable_fd >= 0);
cefc33ae 2916
cefc33ae
LP
2917 if (context->smack_process_label) {
2918 r = mac_smack_apply_pid(0, context->smack_process_label);
2919 if (r < 0)
2920 return r;
2921 }
2922#ifdef SMACK_DEFAULT_PROCESS_LABEL
2923 else {
2924 _cleanup_free_ char *exec_label = NULL;
2925
b83d5050 2926 r = mac_smack_read_fd(executable_fd, SMACK_ATTR_EXEC, &exec_label);
4c701096 2927 if (r < 0 && !IN_SET(r, -ENODATA, -EOPNOTSUPP))
cefc33ae
LP
2928 return r;
2929
2930 r = mac_smack_apply_pid(0, exec_label ? : SMACK_DEFAULT_PROCESS_LABEL);
2931 if (r < 0)
2932 return r;
2933 }
cefc33ae
LP
2934#endif
2935
2936 return 0;
2937}
92b423b9 2938#endif
cefc33ae 2939
6c47cd7d
LP
2940static int compile_bind_mounts(
2941 const ExecContext *context,
2942 const ExecParameters *params,
2943 BindMount **ret_bind_mounts,
da6053d0 2944 size_t *ret_n_bind_mounts,
6c47cd7d
LP
2945 char ***ret_empty_directories) {
2946
2947 _cleanup_strv_free_ char **empty_directories = NULL;
2948 BindMount *bind_mounts;
5b10116e 2949 size_t n, h = 0;
6c47cd7d
LP
2950 int r;
2951
2952 assert(context);
2953 assert(params);
2954 assert(ret_bind_mounts);
2955 assert(ret_n_bind_mounts);
2956 assert(ret_empty_directories);
2957
2958 n = context->n_bind_mounts;
5b10116e 2959 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
6c47cd7d
LP
2960 if (!params->prefix[t])
2961 continue;
2962
2963 n += strv_length(context->directories[t].paths);
2964 }
2965
2966 if (n <= 0) {
2967 *ret_bind_mounts = NULL;
2968 *ret_n_bind_mounts = 0;
2969 *ret_empty_directories = NULL;
2970 return 0;
2971 }
2972
2973 bind_mounts = new(BindMount, n);
2974 if (!bind_mounts)
2975 return -ENOMEM;
2976
5b10116e 2977 for (size_t i = 0; i < context->n_bind_mounts; i++) {
6c47cd7d
LP
2978 BindMount *item = context->bind_mounts + i;
2979 char *s, *d;
2980
2981 s = strdup(item->source);
2982 if (!s) {
2983 r = -ENOMEM;
2984 goto finish;
2985 }
2986
2987 d = strdup(item->destination);
2988 if (!d) {
2989 free(s);
2990 r = -ENOMEM;
2991 goto finish;
2992 }
2993
2994 bind_mounts[h++] = (BindMount) {
2995 .source = s,
2996 .destination = d,
2997 .read_only = item->read_only,
2998 .recursive = item->recursive,
2999 .ignore_enoent = item->ignore_enoent,
3000 };
3001 }
3002
5b10116e 3003 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
6c47cd7d
LP
3004 char **suffix;
3005
3006 if (!params->prefix[t])
3007 continue;
3008
3009 if (strv_isempty(context->directories[t].paths))
3010 continue;
3011
494d0247 3012 if (exec_directory_is_private(context, t) &&
74e12520 3013 !exec_context_with_rootfs(context)) {
6c47cd7d
LP
3014 char *private_root;
3015
3016 /* So this is for a dynamic user, and we need to make sure the process can access its own
3017 * directory. For that we overmount the usually inaccessible "private" subdirectory with a
3018 * tmpfs that makes it accessible and is empty except for the submounts we do this for. */
3019
657ee2d8 3020 private_root = path_join(params->prefix[t], "private");
6c47cd7d
LP
3021 if (!private_root) {
3022 r = -ENOMEM;
3023 goto finish;
3024 }
3025
3026 r = strv_consume(&empty_directories, private_root);
a635a7ae 3027 if (r < 0)
6c47cd7d 3028 goto finish;
6c47cd7d
LP
3029 }
3030
3031 STRV_FOREACH(suffix, context->directories[t].paths) {
3032 char *s, *d;
3033
494d0247 3034 if (exec_directory_is_private(context, t))
657ee2d8 3035 s = path_join(params->prefix[t], "private", *suffix);
6c47cd7d 3036 else
657ee2d8 3037 s = path_join(params->prefix[t], *suffix);
6c47cd7d
LP
3038 if (!s) {
3039 r = -ENOMEM;
3040 goto finish;
3041 }
3042
494d0247 3043 if (exec_directory_is_private(context, t) &&
74e12520 3044 exec_context_with_rootfs(context))
5609f688
YW
3045 /* When RootDirectory= or RootImage= are set, then the symbolic link to the private
3046 * directory is not created on the root directory. So, let's bind-mount the directory
3047 * on the 'non-private' place. */
657ee2d8 3048 d = path_join(params->prefix[t], *suffix);
5609f688
YW
3049 else
3050 d = strdup(s);
6c47cd7d
LP
3051 if (!d) {
3052 free(s);
3053 r = -ENOMEM;
3054 goto finish;
3055 }
3056
3057 bind_mounts[h++] = (BindMount) {
3058 .source = s,
3059 .destination = d,
3060 .read_only = false,
9ce4e4b0 3061 .nosuid = context->dynamic_user, /* don't allow suid/sgid when DynamicUser= is on */
6c47cd7d
LP
3062 .recursive = true,
3063 .ignore_enoent = false,
3064 };
3065 }
3066 }
3067
3068 assert(h == n);
3069
3070 *ret_bind_mounts = bind_mounts;
3071 *ret_n_bind_mounts = n;
ae2a15bc 3072 *ret_empty_directories = TAKE_PTR(empty_directories);
6c47cd7d
LP
3073
3074 return (int) n;
3075
3076finish:
3077 bind_mount_free_many(bind_mounts, h);
3078 return r;
3079}
3080
4e677599
LP
3081static bool insist_on_sandboxing(
3082 const ExecContext *context,
3083 const char *root_dir,
3084 const char *root_image,
3085 const BindMount *bind_mounts,
3086 size_t n_bind_mounts) {
3087
4e677599
LP
3088 assert(context);
3089 assert(n_bind_mounts == 0 || bind_mounts);
3090
3091 /* Checks whether we need to insist on fs namespacing. i.e. whether we have settings configured that
86b52a39 3092 * would alter the view on the file system beyond making things read-only or invisible, i.e. would
4e677599
LP
3093 * rearrange stuff in a way we cannot ignore gracefully. */
3094
3095 if (context->n_temporary_filesystems > 0)
3096 return true;
3097
3098 if (root_dir || root_image)
3099 return true;
3100
b3d13314
LB
3101 if (context->n_mount_images > 0)
3102 return true;
3103
4e677599
LP
3104 if (context->dynamic_user)
3105 return true;
3106
3107 /* If there are any bind mounts set that don't map back onto themselves, fs namespacing becomes
3108 * essential. */
5b10116e 3109 for (size_t i = 0; i < n_bind_mounts; i++)
4e677599
LP
3110 if (!path_equal(bind_mounts[i].source, bind_mounts[i].destination))
3111 return true;
3112
91dd5f7c
LP
3113 if (context->log_namespace)
3114 return true;
3115
4e677599
LP
3116 return false;
3117}
3118
6818c54c 3119static int apply_mount_namespace(
34cf6c43 3120 const Unit *u,
9f71ba8d 3121 ExecCommandFlags command_flags,
6818c54c
LP
3122 const ExecContext *context,
3123 const ExecParameters *params,
7cc5ef5f
ZJS
3124 const ExecRuntime *runtime,
3125 char **error_path) {
6818c54c 3126
7bcef4ef 3127 _cleanup_strv_free_ char **empty_directories = NULL;
56a13a49 3128 const char *tmp_dir = NULL, *var_tmp_dir = NULL;
915e6d16 3129 const char *root_dir = NULL, *root_image = NULL;
5e8deb94 3130 _cleanup_free_ char *creds_path = NULL, *incoming_dir = NULL, *propagate_dir = NULL;
228af36f 3131 NamespaceInfo ns_info;
165a31c0 3132 bool needs_sandboxing;
6c47cd7d 3133 BindMount *bind_mounts = NULL;
da6053d0 3134 size_t n_bind_mounts = 0;
6818c54c 3135 int r;
93c6bb51 3136
2b3c1b9e
DH
3137 assert(context);
3138
915e6d16
LP
3139 if (params->flags & EXEC_APPLY_CHROOT) {
3140 root_image = context->root_image;
3141
3142 if (!root_image)
3143 root_dir = context->root_directory;
3144 }
93c6bb51 3145
6c47cd7d
LP
3146 r = compile_bind_mounts(context, params, &bind_mounts, &n_bind_mounts, &empty_directories);
3147 if (r < 0)
3148 return r;
3149
9f71ba8d 3150 needs_sandboxing = (params->flags & EXEC_APPLY_SANDBOXING) && !(command_flags & EXEC_COMMAND_FULLY_PRIVILEGED);
ecf63c91
NJ
3151 if (needs_sandboxing) {
3152 /* The runtime struct only contains the parent of the private /tmp,
3153 * which is non-accessible to world users. Inside of it there's a /tmp
56a13a49
ZJS
3154 * that is sticky, and that's the one we want to use here.
3155 * This does not apply when we are using /run/systemd/empty as fallback. */
ecf63c91
NJ
3156
3157 if (context->private_tmp && runtime) {
56a13a49
ZJS
3158 if (streq_ptr(runtime->tmp_dir, RUN_SYSTEMD_EMPTY))
3159 tmp_dir = runtime->tmp_dir;
3160 else if (runtime->tmp_dir)
3161 tmp_dir = strjoina(runtime->tmp_dir, "/tmp");
3162
3163 if (streq_ptr(runtime->var_tmp_dir, RUN_SYSTEMD_EMPTY))
3164 var_tmp_dir = runtime->var_tmp_dir;
f63ef937 3165 else if (runtime->var_tmp_dir)
56a13a49 3166 var_tmp_dir = strjoina(runtime->var_tmp_dir, "/tmp");
ecf63c91
NJ
3167 }
3168
b5a33299
YW
3169 ns_info = (NamespaceInfo) {
3170 .ignore_protect_paths = false,
3171 .private_dev = context->private_devices,
3172 .protect_control_groups = context->protect_control_groups,
3173 .protect_kernel_tunables = context->protect_kernel_tunables,
3174 .protect_kernel_modules = context->protect_kernel_modules,
94a7b275 3175 .protect_kernel_logs = context->protect_kernel_logs,
aecd5ac6 3176 .protect_hostname = context->protect_hostname,
5e98086d 3177 .mount_apivfs = exec_context_get_effective_mount_apivfs(context),
228af36f 3178 .private_mounts = context->private_mounts,
52b3d652
LP
3179 .protect_home = context->protect_home,
3180 .protect_system = context->protect_system,
4e399953
LP
3181 .protect_proc = context->protect_proc,
3182 .proc_subset = context->proc_subset,
80271a44 3183 .private_ipc = context->private_ipc || context->ipc_namespace_path,
b5a33299 3184 };
ecf63c91 3185 } else if (!context->dynamic_user && root_dir)
228af36f
LP
3186 /*
3187 * If DynamicUser=no and RootDirectory= is set then lets pass a relaxed
3188 * sandbox info, otherwise enforce it, don't ignore protected paths and
3189 * fail if we are enable to apply the sandbox inside the mount namespace.
3190 */
3191 ns_info = (NamespaceInfo) {
3192 .ignore_protect_paths = true,
3193 };
3194 else
3195 ns_info = (NamespaceInfo) {};
b5a33299 3196
37ed15d7
FB
3197 if (context->mount_flags == MS_SHARED)
3198 log_unit_debug(u, "shared mount propagation hidden by other fs namespacing unit settings: ignoring");
3199
a631cbfa
LP
3200 if (exec_context_has_credentials(context) &&
3201 params->prefix[EXEC_DIRECTORY_RUNTIME] &&
3202 FLAGS_SET(params->flags, EXEC_WRITE_CREDENTIALS)) {
bbb4e7f3 3203 creds_path = path_join(params->prefix[EXEC_DIRECTORY_RUNTIME], "credentials", u->id);
8062e643
YW
3204 if (!creds_path) {
3205 r = -ENOMEM;
3206 goto finalize;
3207 }
bbb4e7f3
LP
3208 }
3209
5e8deb94
LB
3210 if (MANAGER_IS_SYSTEM(u->manager)) {
3211 propagate_dir = path_join("/run/systemd/propagate/", u->id);
f2550b98
LP
3212 if (!propagate_dir) {
3213 r = -ENOMEM;
3214 goto finalize;
3215 }
3216
5e8deb94 3217 incoming_dir = strdup("/run/systemd/incoming");
f2550b98
LP
3218 if (!incoming_dir) {
3219 r = -ENOMEM;
3220 goto finalize;
3221 }
5e8deb94
LB
3222 }
3223
18d73705 3224 r = setup_namespace(root_dir, root_image, context->root_image_options,
7bcef4ef 3225 &ns_info, context->read_write_paths,
165a31c0
LP
3226 needs_sandboxing ? context->read_only_paths : NULL,
3227 needs_sandboxing ? context->inaccessible_paths : NULL,
ddc155b2
TM
3228 needs_sandboxing ? context->exec_paths : NULL,
3229 needs_sandboxing ? context->no_exec_paths : NULL,
6c47cd7d
LP
3230 empty_directories,
3231 bind_mounts,
3232 n_bind_mounts,
2abd4e38
YW
3233 context->temporary_filesystems,
3234 context->n_temporary_filesystems,
b3d13314
LB
3235 context->mount_images,
3236 context->n_mount_images,
56a13a49
ZJS
3237 tmp_dir,
3238 var_tmp_dir,
bbb4e7f3 3239 creds_path,
91dd5f7c 3240 context->log_namespace,
915e6d16 3241 context->mount_flags,
d4d55b0d
LB
3242 context->root_hash, context->root_hash_size, context->root_hash_path,
3243 context->root_hash_sig, context->root_hash_sig_size, context->root_hash_sig_path,
3244 context->root_verity,
93f59701
LB
3245 context->extension_images,
3246 context->n_extension_images,
5e8deb94
LB
3247 propagate_dir,
3248 incoming_dir,
3bdc25a4 3249 root_dir || root_image ? params->notify_socket : NULL,
8d251485 3250 DISSECT_IMAGE_DISCARD_ON_LOOP|DISSECT_IMAGE_RELAX_VAR_CHECK|DISSECT_IMAGE_FSCK,
7cc5ef5f 3251 error_path);
93c6bb51 3252
1beab8b0 3253 /* If we couldn't set up the namespace this is probably due to a missing capability. setup_namespace() reports
5238e957 3254 * that with a special, recognizable error ENOANO. In this case, silently proceed, but only if exclusively
1beab8b0
LP
3255 * sandboxing options were used, i.e. nothing such as RootDirectory= or BindMount= that would result in a
3256 * completely different execution environment. */
aca835ed 3257 if (r == -ENOANO) {
4e677599
LP
3258 if (insist_on_sandboxing(
3259 context,
3260 root_dir, root_image,
3261 bind_mounts,
3262 n_bind_mounts)) {
3263 log_unit_debug(u, "Failed to set up namespace, and refusing to continue since the selected namespacing options alter mount environment non-trivially.\n"
3264 "Bind mounts: %zu, temporary filesystems: %zu, root directory: %s, root image: %s, dynamic user: %s",
3265 n_bind_mounts, context->n_temporary_filesystems, yes_no(root_dir), yes_no(root_image), yes_no(context->dynamic_user));
3266
3267 r = -EOPNOTSUPP;
3268 } else {
aca835ed 3269 log_unit_debug(u, "Failed to set up namespace, assuming containerized execution and ignoring.");
4e677599 3270 r = 0;
aca835ed 3271 }
93c6bb51
DH
3272 }
3273
8062e643 3274finalize:
4e677599 3275 bind_mount_free_many(bind_mounts, n_bind_mounts);
93c6bb51
DH
3276 return r;
3277}
3278
915e6d16
LP
3279static int apply_working_directory(
3280 const ExecContext *context,
3281 const ExecParameters *params,
3282 const char *home,
376fecf6 3283 int *exit_status) {
915e6d16 3284
6732edab 3285 const char *d, *wd;
2b3c1b9e
DH
3286
3287 assert(context);
376fecf6 3288 assert(exit_status);
2b3c1b9e 3289
6732edab
LP
3290 if (context->working_directory_home) {
3291
376fecf6
LP
3292 if (!home) {
3293 *exit_status = EXIT_CHDIR;
6732edab 3294 return -ENXIO;
376fecf6 3295 }
6732edab 3296
2b3c1b9e 3297 wd = home;
6732edab 3298
14eb3285
LP
3299 } else
3300 wd = empty_to_root(context->working_directory);
e7f1e7c6 3301
fa97f630 3302 if (params->flags & EXEC_APPLY_CHROOT)
2b3c1b9e 3303 d = wd;
fa97f630 3304 else
3b0e5bb5 3305 d = prefix_roota(context->root_directory, wd);
e7f1e7c6 3306
376fecf6
LP
3307 if (chdir(d) < 0 && !context->working_directory_missing_ok) {
3308 *exit_status = EXIT_CHDIR;
2b3c1b9e 3309 return -errno;
376fecf6 3310 }
e7f1e7c6
DH
3311
3312 return 0;
3313}
3314
fa97f630
JB
3315static int apply_root_directory(
3316 const ExecContext *context,
3317 const ExecParameters *params,
3318 const bool needs_mount_ns,
3319 int *exit_status) {
3320
3321 assert(context);
3322 assert(exit_status);
3323
5b10116e 3324 if (params->flags & EXEC_APPLY_CHROOT)
fa97f630
JB
3325 if (!needs_mount_ns && context->root_directory)
3326 if (chroot(context->root_directory) < 0) {
3327 *exit_status = EXIT_CHROOT;
3328 return -errno;
3329 }
fa97f630
JB
3330
3331 return 0;
3332}
3333
b1edf445 3334static int setup_keyring(
34cf6c43 3335 const Unit *u,
b1edf445
LP
3336 const ExecContext *context,
3337 const ExecParameters *p,
3338 uid_t uid, gid_t gid) {
3339
74dd6b51 3340 key_serial_t keyring;
e64c2d0b
DJL
3341 int r = 0;
3342 uid_t saved_uid;
3343 gid_t saved_gid;
74dd6b51
LP
3344
3345 assert(u);
b1edf445 3346 assert(context);
74dd6b51
LP
3347 assert(p);
3348
3349 /* Let's set up a new per-service "session" kernel keyring for each system service. This has the benefit that
3350 * each service runs with its own keyring shared among all processes of the service, but with no hook-up beyond
3351 * that scope, and in particular no link to the per-UID keyring. If we don't do this the keyring will be
3352 * automatically created on-demand and then linked to the per-UID keyring, by the kernel. The kernel's built-in
3353 * on-demand behaviour is very appropriate for login users, but probably not so much for system services, where
3354 * UIDs are not necessarily specific to a service but reused (at least in the case of UID 0). */
3355
b1edf445
LP
3356 if (context->keyring_mode == EXEC_KEYRING_INHERIT)
3357 return 0;
3358
e64c2d0b
DJL
3359 /* Acquiring a reference to the user keyring is nasty. We briefly change identity in order to get things set up
3360 * properly by the kernel. If we don't do that then we can't create it atomically, and that sucks for parallel
3361 * execution. This mimics what pam_keyinit does, too. Setting up session keyring, to be owned by the right user
3362 * & group is just as nasty as acquiring a reference to the user keyring. */
3363
3364 saved_uid = getuid();
3365 saved_gid = getgid();
3366
3367 if (gid_is_valid(gid) && gid != saved_gid) {
3368 if (setregid(gid, -1) < 0)
3369 return log_unit_error_errno(u, errno, "Failed to change GID for user keyring: %m");
3370 }
3371
3372 if (uid_is_valid(uid) && uid != saved_uid) {
3373 if (setreuid(uid, -1) < 0) {
3374 r = log_unit_error_errno(u, errno, "Failed to change UID for user keyring: %m");
3375 goto out;
3376 }
3377 }
3378
74dd6b51
LP
3379 keyring = keyctl(KEYCTL_JOIN_SESSION_KEYRING, 0, 0, 0, 0);
3380 if (keyring == -1) {
3381 if (errno == ENOSYS)
8002fb97 3382 log_unit_debug_errno(u, errno, "Kernel keyring not supported, ignoring.");
065b4774 3383 else if (ERRNO_IS_PRIVILEGE(errno))
8002fb97 3384 log_unit_debug_errno(u, errno, "Kernel keyring access prohibited, ignoring.");
74dd6b51 3385 else if (errno == EDQUOT)
8002fb97 3386 log_unit_debug_errno(u, errno, "Out of kernel keyrings to allocate, ignoring.");
74dd6b51 3387 else
e64c2d0b 3388 r = log_unit_error_errno(u, errno, "Setting up kernel keyring failed: %m");
74dd6b51 3389
e64c2d0b 3390 goto out;
74dd6b51
LP
3391 }
3392
e64c2d0b
DJL
3393 /* When requested link the user keyring into the session keyring. */
3394 if (context->keyring_mode == EXEC_KEYRING_SHARED) {
3395
3396 if (keyctl(KEYCTL_LINK,
3397 KEY_SPEC_USER_KEYRING,
3398 KEY_SPEC_SESSION_KEYRING, 0, 0) < 0) {
3399 r = log_unit_error_errno(u, errno, "Failed to link user keyring into session keyring: %m");
3400 goto out;
3401 }
3402 }
3403
3404 /* Restore uid/gid back */
3405 if (uid_is_valid(uid) && uid != saved_uid) {
3406 if (setreuid(saved_uid, -1) < 0) {
3407 r = log_unit_error_errno(u, errno, "Failed to change UID back for user keyring: %m");
3408 goto out;
3409 }
3410 }
3411
3412 if (gid_is_valid(gid) && gid != saved_gid) {
3413 if (setregid(saved_gid, -1) < 0)
3414 return log_unit_error_errno(u, errno, "Failed to change GID back for user keyring: %m");
3415 }
3416
3417 /* Populate they keyring with the invocation ID by default, as original saved_uid. */
b3415f5d
LP
3418 if (!sd_id128_is_null(u->invocation_id)) {
3419 key_serial_t key;
3420
3421 key = add_key("user", "invocation_id", &u->invocation_id, sizeof(u->invocation_id), KEY_SPEC_SESSION_KEYRING);
3422 if (key == -1)
8002fb97 3423 log_unit_debug_errno(u, errno, "Failed to add invocation ID to keyring, ignoring: %m");
b3415f5d
LP
3424 else {
3425 if (keyctl(KEYCTL_SETPERM, key,
3426 KEY_POS_VIEW|KEY_POS_READ|KEY_POS_SEARCH|
3427 KEY_USR_VIEW|KEY_USR_READ|KEY_USR_SEARCH, 0, 0) < 0)
e64c2d0b 3428 r = log_unit_error_errno(u, errno, "Failed to restrict invocation ID permission: %m");
b3415f5d
LP
3429 }
3430 }
3431
e64c2d0b 3432out:
37b22b3b 3433 /* Revert back uid & gid for the last time, and exit */
e64c2d0b
DJL
3434 /* no extra logging, as only the first already reported error matters */
3435 if (getuid() != saved_uid)
3436 (void) setreuid(saved_uid, -1);
b1edf445 3437
e64c2d0b
DJL
3438 if (getgid() != saved_gid)
3439 (void) setregid(saved_gid, -1);
b1edf445 3440
e64c2d0b 3441 return r;
74dd6b51
LP
3442}
3443
3042bbeb 3444static void append_socket_pair(int *array, size_t *n, const int pair[static 2]) {
29206d46
LP
3445 assert(array);
3446 assert(n);
2caa38e9 3447 assert(pair);
29206d46
LP
3448
3449 if (pair[0] >= 0)
3450 array[(*n)++] = pair[0];
3451 if (pair[1] >= 0)
3452 array[(*n)++] = pair[1];
3453}
3454
a34ceba6
LP
3455static int close_remaining_fds(
3456 const ExecParameters *params,
34cf6c43
YW
3457 const ExecRuntime *runtime,
3458 const DynamicCreds *dcreds,
00d9ef85 3459 int user_lookup_fd,
a34ceba6 3460 int socket_fd,
5b8d1f6b 3461 const int *fds, size_t n_fds) {
a34ceba6 3462
da6053d0 3463 size_t n_dont_close = 0;
00d9ef85 3464 int dont_close[n_fds + 12];
a34ceba6
LP
3465
3466 assert(params);
3467
3468 if (params->stdin_fd >= 0)
3469 dont_close[n_dont_close++] = params->stdin_fd;
3470 if (params->stdout_fd >= 0)
3471 dont_close[n_dont_close++] = params->stdout_fd;
3472 if (params->stderr_fd >= 0)
3473 dont_close[n_dont_close++] = params->stderr_fd;
3474
3475 if (socket_fd >= 0)
3476 dont_close[n_dont_close++] = socket_fd;
3477 if (n_fds > 0) {
3478 memcpy(dont_close + n_dont_close, fds, sizeof(int) * n_fds);
3479 n_dont_close += n_fds;
3480 }
3481
a70581ff 3482 if (runtime) {
29206d46 3483 append_socket_pair(dont_close, &n_dont_close, runtime->netns_storage_socket);
a70581ff
XR
3484 append_socket_pair(dont_close, &n_dont_close, runtime->ipcns_storage_socket);
3485 }
29206d46
LP
3486
3487 if (dcreds) {
3488 if (dcreds->user)
3489 append_socket_pair(dont_close, &n_dont_close, dcreds->user->storage_socket);
3490 if (dcreds->group)
3491 append_socket_pair(dont_close, &n_dont_close, dcreds->group->storage_socket);
a34ceba6
LP
3492 }
3493
00d9ef85
LP
3494 if (user_lookup_fd >= 0)
3495 dont_close[n_dont_close++] = user_lookup_fd;
3496
a34ceba6
LP
3497 return close_all_fds(dont_close, n_dont_close);
3498}
3499
00d9ef85
LP
3500static int send_user_lookup(
3501 Unit *unit,
3502 int user_lookup_fd,
3503 uid_t uid,
3504 gid_t gid) {
3505
3506 assert(unit);
3507
3508 /* Send the resolved UID/GID to PID 1 after we learnt it. We send a single datagram, containing the UID/GID
3509 * data as well as the unit name. Note that we suppress sending this if no user/group to resolve was
3510 * specified. */
3511
3512 if (user_lookup_fd < 0)
3513 return 0;
3514
3515 if (!uid_is_valid(uid) && !gid_is_valid(gid))
3516 return 0;
3517
3518 if (writev(user_lookup_fd,
3519 (struct iovec[]) {
e6a7ec4b
LP
3520 IOVEC_INIT(&uid, sizeof(uid)),
3521 IOVEC_INIT(&gid, sizeof(gid)),
3522 IOVEC_INIT_STRING(unit->id) }, 3) < 0)
00d9ef85
LP
3523 return -errno;
3524
3525 return 0;
3526}
3527
6732edab
LP
3528static int acquire_home(const ExecContext *c, uid_t uid, const char** home, char **buf) {
3529 int r;
3530
3531 assert(c);
3532 assert(home);
3533 assert(buf);
3534
3535 /* If WorkingDirectory=~ is set, try to acquire a usable home directory. */
3536
3537 if (*home)
3538 return 0;
3539
3540 if (!c->working_directory_home)
3541 return 0;
3542
6732edab
LP
3543 r = get_home_dir(buf);
3544 if (r < 0)
3545 return r;
3546
3547 *home = *buf;
3548 return 1;
3549}
3550
da50b85a
LP
3551static int compile_suggested_paths(const ExecContext *c, const ExecParameters *p, char ***ret) {
3552 _cleanup_strv_free_ char ** list = NULL;
da50b85a
LP
3553 int r;
3554
3555 assert(c);
3556 assert(p);
3557 assert(ret);
3558
3559 assert(c->dynamic_user);
3560
3561 /* Compile a list of paths that it might make sense to read the owning UID from to use as initial candidate for
3562 * dynamic UID allocation, in order to save us from doing costly recursive chown()s of the special
3563 * directories. */
3564
5b10116e 3565 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
da50b85a
LP
3566 char **i;
3567
3568 if (t == EXEC_DIRECTORY_CONFIGURATION)
3569 continue;
3570
3571 if (!p->prefix[t])
3572 continue;
3573
3574 STRV_FOREACH(i, c->directories[t].paths) {
3575 char *e;
3576
494d0247 3577 if (exec_directory_is_private(c, t))
657ee2d8 3578 e = path_join(p->prefix[t], "private", *i);
494d0247
YW
3579 else
3580 e = path_join(p->prefix[t], *i);
da50b85a
LP
3581 if (!e)
3582 return -ENOMEM;
3583
3584 r = strv_consume(&list, e);
3585 if (r < 0)
3586 return r;
3587 }
3588 }
3589
ae2a15bc 3590 *ret = TAKE_PTR(list);
da50b85a
LP
3591
3592 return 0;
3593}
3594
34cf6c43
YW
3595static char *exec_command_line(char **argv);
3596
78f93209
LP
3597static int exec_parameters_get_cgroup_path(const ExecParameters *params, char **ret) {
3598 bool using_subcgroup;
3599 char *p;
3600
3601 assert(params);
3602 assert(ret);
3603
3604 if (!params->cgroup_path)
3605 return -EINVAL;
3606
3607 /* If we are called for a unit where cgroup delegation is on, and the payload created its own populated
3608 * subcgroup (which we expect it to do, after all it asked for delegation), then we cannot place the control
3609 * processes started after the main unit's process in the unit's main cgroup because it is now an inner one,
3610 * and inner cgroups may not contain processes. Hence, if delegation is on, and this is a control process,
3611 * let's use ".control" as subcgroup instead. Note that we do so only for ExecStartPost=, ExecReload=,
3612 * ExecStop=, ExecStopPost=, i.e. for the commands where the main process is already forked. For ExecStartPre=
3613 * this is not necessary, the cgroup is still empty. We distinguish these cases with the EXEC_CONTROL_CGROUP
3614 * flag, which is only passed for the former statements, not for the latter. */
3615
3616 using_subcgroup = FLAGS_SET(params->flags, EXEC_CONTROL_CGROUP|EXEC_CGROUP_DELEGATE|EXEC_IS_CONTROL);
3617 if (using_subcgroup)
657ee2d8 3618 p = path_join(params->cgroup_path, ".control");
78f93209
LP
3619 else
3620 p = strdup(params->cgroup_path);
3621 if (!p)
3622 return -ENOMEM;
3623
3624 *ret = p;
3625 return using_subcgroup;
3626}
3627
e2b2fb7f
MS
3628static int exec_context_cpu_affinity_from_numa(const ExecContext *c, CPUSet *ret) {
3629 _cleanup_(cpu_set_reset) CPUSet s = {};
3630 int r;
3631
3632 assert(c);
3633 assert(ret);
3634
3635 if (!c->numa_policy.nodes.set) {
3636 log_debug("Can't derive CPU affinity mask from NUMA mask because NUMA mask is not set, ignoring");
3637 return 0;
3638 }
3639
3640 r = numa_to_cpu_set(&c->numa_policy, &s);
3641 if (r < 0)
3642 return r;
3643
3644 cpu_set_reset(ret);
3645
3646 return cpu_set_add_all(ret, &s);
3647}
3648
3649bool exec_context_get_cpu_affinity_from_numa(const ExecContext *c) {
3650 assert(c);
3651
3652 return c->cpu_affinity_from_numa;
3653}
3654
1da37e58
ZJS
3655static int add_shifted_fd(int *fds, size_t fds_size, size_t *n_fds, int fd, int *ret_fd) {
3656 int r;
3657
3658 assert(fds);
3659 assert(n_fds);
3660 assert(*n_fds < fds_size);
3661 assert(ret_fd);
3662
3663 if (fd < 0) {
3664 *ret_fd = -1;
3665 return 0;
3666 }
3667
3668 if (fd < 3 + (int) *n_fds) {
3669 /* Let's move the fd up, so that it's outside of the fd range we will use to store
3670 * the fds we pass to the process (or which are closed only during execve). */
3671
3672 r = fcntl(fd, F_DUPFD_CLOEXEC, 3 + (int) *n_fds);
3673 if (r < 0)
3674 return -errno;
3675
3676 CLOSE_AND_REPLACE(fd, r);
3677 }
3678
3679 *ret_fd = fds[*n_fds] = fd;
3680 (*n_fds) ++;
3681 return 1;
3682}
3683
ff0af2a1 3684static int exec_child(
f2341e0a 3685 Unit *unit,
34cf6c43 3686 const ExecCommand *command,
ff0af2a1
LP
3687 const ExecContext *context,
3688 const ExecParameters *params,
3689 ExecRuntime *runtime,
29206d46 3690 DynamicCreds *dcreds,
ff0af2a1 3691 int socket_fd,
2caa38e9 3692 const int named_iofds[static 3],
4c47affc 3693 int *fds,
da6053d0 3694 size_t n_socket_fds,
25b583d7 3695 size_t n_storage_fds,
ff0af2a1 3696 char **files_env,
00d9ef85 3697 int user_lookup_fd,
12145637 3698 int *exit_status) {
d35fbf6b 3699
7ca69792 3700 _cleanup_strv_free_ char **our_env = NULL, **pass_env = NULL, **accum_env = NULL, **replaced_argv = NULL;
1da37e58 3701 int r, ngids = 0, exec_fd;
4d885bd3
DH
3702 _cleanup_free_ gid_t *supplementary_gids = NULL;
3703 const char *username = NULL, *groupname = NULL;
5686391b 3704 _cleanup_free_ char *home_buffer = NULL;
2b3c1b9e 3705 const char *home = NULL, *shell = NULL;
7ca69792 3706 char **final_argv = NULL;
7bce046b
LP
3707 dev_t journal_stream_dev = 0;
3708 ino_t journal_stream_ino = 0;
5749f855 3709 bool userns_set_up = false;
165a31c0
LP
3710 bool needs_sandboxing, /* Do we need to set up full sandboxing? (i.e. all namespacing, all MAC stuff, caps, yadda yadda */
3711 needs_setuid, /* Do we need to do the actual setresuid()/setresgid() calls? */
3712 needs_mount_namespace, /* Do we need to set up a mount namespace for this kernel? */
3713 needs_ambient_hack; /* Do we need to apply the ambient capabilities hack? */
349cc4a5 3714#if HAVE_SELINUX
7f59dd35 3715 _cleanup_free_ char *mac_selinux_context_net = NULL;
43b1f709 3716 bool use_selinux = false;
ecfbc84f 3717#endif
f9fa32f0 3718#if ENABLE_SMACK
43b1f709 3719 bool use_smack = false;
ecfbc84f 3720#endif
349cc4a5 3721#if HAVE_APPARMOR
43b1f709 3722 bool use_apparmor = false;
ecfbc84f 3723#endif
5749f855
AZ
3724 uid_t saved_uid = getuid();
3725 gid_t saved_gid = getgid();
fed1e721
LP
3726 uid_t uid = UID_INVALID;
3727 gid_t gid = GID_INVALID;
1da37e58
ZJS
3728 size_t n_fds = n_socket_fds + n_storage_fds, /* fds to pass to the child */
3729 n_keep_fds; /* total number of fds not to close */
165a31c0 3730 int secure_bits;
afb11bf1
DG
3731 _cleanup_free_ gid_t *gids_after_pam = NULL;
3732 int ngids_after_pam = 0;
034c6ed7 3733
f2341e0a 3734 assert(unit);
5cb5a6ff
LP
3735 assert(command);
3736 assert(context);
d35fbf6b 3737 assert(params);
ff0af2a1 3738 assert(exit_status);
d35fbf6b
DM
3739
3740 rename_process_from_path(command->path);
3741
9c274488
LP
3742 /* We reset exactly these signals, since they are the only ones we set to SIG_IGN in the main
3743 * daemon. All others we leave untouched because we set them to SIG_DFL or a valid handler initially,
3744 * both of which will be demoted to SIG_DFL. */
ce30c8dc 3745 (void) default_signals(SIGNALS_CRASH_HANDLER,
9c274488 3746 SIGNALS_IGNORE);
d35fbf6b
DM
3747
3748 if (context->ignore_sigpipe)
9c274488 3749 (void) ignore_signals(SIGPIPE);
d35fbf6b 3750
ff0af2a1
LP
3751 r = reset_signal_mask();
3752 if (r < 0) {
3753 *exit_status = EXIT_SIGNAL_MASK;
12145637 3754 return log_unit_error_errno(unit, r, "Failed to set process signal mask: %m");
d35fbf6b 3755 }
034c6ed7 3756
d35fbf6b
DM
3757 if (params->idle_pipe)
3758 do_idle_pipe_dance(params->idle_pipe);
4f2d528d 3759
2c027c62
LP
3760 /* Close fds we don't need very early to make sure we don't block init reexecution because it cannot bind its
3761 * sockets. Among the fds we close are the logging fds, and we want to keep them closed, so that we don't have
3762 * any fds open we don't really want open during the transition. In order to make logging work, we switch the
3763 * log subsystem into open_when_needed mode, so that it reopens the logs on every single log call. */
ff0af2a1 3764
d35fbf6b 3765 log_forget_fds();
2c027c62 3766 log_set_open_when_needed(true);
4f2d528d 3767
40a80078
LP
3768 /* In case anything used libc syslog(), close this here, too */
3769 closelog();
3770
b83d5050 3771 int keep_fds[n_fds + 2];
1da37e58
ZJS
3772 memcpy_safe(keep_fds, fds, n_fds * sizeof(int));
3773 n_keep_fds = n_fds;
3774
3775 r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, params->exec_fd, &exec_fd);
3776 if (r < 0) {
3777 *exit_status = EXIT_FDS;
3778 return log_unit_error_errno(unit, r, "Failed to shift fd and set FD_CLOEXEC: %m");
3779 }
3780
3781 r = close_remaining_fds(params, runtime, dcreds, user_lookup_fd, socket_fd, keep_fds, n_keep_fds);
ff0af2a1
LP
3782 if (r < 0) {
3783 *exit_status = EXIT_FDS;
12145637 3784 return log_unit_error_errno(unit, r, "Failed to close unwanted file descriptors: %m");
8c7be95e
LP
3785 }
3786
0af07108
ZJS
3787 if (!context->same_pgrp &&
3788 setsid() < 0) {
3789 *exit_status = EXIT_SETSID;
3790 return log_unit_error_errno(unit, errno, "Failed to create new process session: %m");
3791 }
9e2f7c11 3792
1e22b5cd 3793 exec_context_tty_reset(context, params);
d35fbf6b 3794
c891efaf 3795 if (unit_shall_confirm_spawn(unit)) {
7d5ceb64 3796 const char *vc = params->confirm_spawn;
3b20f877
FB
3797 _cleanup_free_ char *cmdline = NULL;
3798
ee39ca20 3799 cmdline = exec_command_line(command->argv);
3b20f877 3800 if (!cmdline) {
0460aa5c 3801 *exit_status = EXIT_MEMORY;
12145637 3802 return log_oom();
3b20f877 3803 }
d35fbf6b 3804
eedf223a 3805 r = ask_for_confirmation(vc, unit, cmdline);
3b20f877
FB
3806 if (r != CONFIRM_EXECUTE) {
3807 if (r == CONFIRM_PRETEND_SUCCESS) {
3808 *exit_status = EXIT_SUCCESS;
3809 return 0;
3810 }
ff0af2a1 3811 *exit_status = EXIT_CONFIRM;
0af07108
ZJS
3812 return log_unit_error_errno(unit, SYNTHETIC_ERRNO(ECANCELED),
3813 "Execution cancelled by the user");
d35fbf6b
DM
3814 }
3815 }
1a63a750 3816
d521916d
LP
3817 /* We are about to invoke NSS and PAM modules. Let's tell them what we are doing here, maybe they care. This is
3818 * used by nss-resolve to disable itself when we are about to start systemd-resolved, to avoid deadlocks. Note
3819 * that these env vars do not survive the execve(), which means they really only apply to the PAM and NSS
3820 * invocations themselves. Also note that while we'll only invoke NSS modules involved in user management they
3821 * might internally call into other NSS modules that are involved in hostname resolution, we never know. */
3822 if (setenv("SYSTEMD_ACTIVATION_UNIT", unit->id, true) != 0 ||
3823 setenv("SYSTEMD_ACTIVATION_SCOPE", MANAGER_IS_SYSTEM(unit->manager) ? "system" : "user", true) != 0) {
3824 *exit_status = EXIT_MEMORY;
3825 return log_unit_error_errno(unit, errno, "Failed to update environment: %m");
3826 }
3827
29206d46 3828 if (context->dynamic_user && dcreds) {
da50b85a 3829 _cleanup_strv_free_ char **suggested_paths = NULL;
29206d46 3830
d521916d
LP
3831 /* On top of that, make sure we bypass our own NSS module nss-systemd comprehensively for any NSS
3832 * checks, if DynamicUser=1 is used, as we shouldn't create a feedback loop with ourselves here.*/
409093fe
LP
3833 if (putenv((char*) "SYSTEMD_NSS_DYNAMIC_BYPASS=1") != 0) {
3834 *exit_status = EXIT_USER;
12145637 3835 return log_unit_error_errno(unit, errno, "Failed to update environment: %m");
409093fe
LP
3836 }
3837
da50b85a
LP
3838 r = compile_suggested_paths(context, params, &suggested_paths);
3839 if (r < 0) {
3840 *exit_status = EXIT_MEMORY;
3841 return log_oom();
3842 }
3843
3844 r = dynamic_creds_realize(dcreds, suggested_paths, &uid, &gid);
ff0af2a1
LP
3845 if (r < 0) {
3846 *exit_status = EXIT_USER;
d85ff944
YW
3847 if (r == -EILSEQ)
3848 return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EOPNOTSUPP),
3849 "Failed to update dynamic user credentials: User or group with specified name already exists.");
12145637 3850 return log_unit_error_errno(unit, r, "Failed to update dynamic user credentials: %m");
524daa8c 3851 }
524daa8c 3852
70dd455c 3853 if (!uid_is_valid(uid)) {
29206d46 3854 *exit_status = EXIT_USER;
d85ff944 3855 return log_unit_error_errno(unit, SYNTHETIC_ERRNO(ESRCH), "UID validation failed for \""UID_FMT"\"", uid);
70dd455c
ZJS
3856 }
3857
3858 if (!gid_is_valid(gid)) {
3859 *exit_status = EXIT_USER;
d85ff944 3860 return log_unit_error_errno(unit, SYNTHETIC_ERRNO(ESRCH), "GID validation failed for \""GID_FMT"\"", gid);
29206d46 3861 }
5bc7452b 3862
29206d46
LP
3863 if (dcreds->user)
3864 username = dcreds->user->name;
3865
3866 } else {
4d885bd3
DH
3867 r = get_fixed_user(context, &username, &uid, &gid, &home, &shell);
3868 if (r < 0) {
3869 *exit_status = EXIT_USER;
12145637 3870 return log_unit_error_errno(unit, r, "Failed to determine user credentials: %m");
5bc7452b 3871 }
5bc7452b 3872
4d885bd3
DH
3873 r = get_fixed_group(context, &groupname, &gid);
3874 if (r < 0) {
3875 *exit_status = EXIT_GROUP;
12145637 3876 return log_unit_error_errno(unit, r, "Failed to determine group credentials: %m");
4d885bd3 3877 }
cdc5d5c5 3878 }
29206d46 3879
cdc5d5c5
DH
3880 /* Initialize user supplementary groups and get SupplementaryGroups= ones */
3881 r = get_supplementary_groups(context, username, groupname, gid,
3882 &supplementary_gids, &ngids);
3883 if (r < 0) {
3884 *exit_status = EXIT_GROUP;
12145637 3885 return log_unit_error_errno(unit, r, "Failed to determine supplementary groups: %m");
29206d46 3886 }
5bc7452b 3887
00d9ef85
LP
3888 r = send_user_lookup(unit, user_lookup_fd, uid, gid);
3889 if (r < 0) {
3890 *exit_status = EXIT_USER;
12145637 3891 return log_unit_error_errno(unit, r, "Failed to send user credentials to PID1: %m");
00d9ef85
LP
3892 }
3893
3894 user_lookup_fd = safe_close(user_lookup_fd);
3895
6732edab
LP
3896 r = acquire_home(context, uid, &home, &home_buffer);
3897 if (r < 0) {
3898 *exit_status = EXIT_CHDIR;
12145637 3899 return log_unit_error_errno(unit, r, "Failed to determine $HOME for user: %m");
6732edab
LP
3900 }
3901
d35fbf6b
DM
3902 /* If a socket is connected to STDIN/STDOUT/STDERR, we
3903 * must sure to drop O_NONBLOCK */
3904 if (socket_fd >= 0)
a34ceba6 3905 (void) fd_nonblock(socket_fd, false);
acbb0225 3906
4c70a4a7
MS
3907 /* Journald will try to look-up our cgroup in order to populate _SYSTEMD_CGROUP and _SYSTEMD_UNIT fields.
3908 * Hence we need to migrate to the target cgroup from init.scope before connecting to journald */
3909 if (params->cgroup_path) {
3910 _cleanup_free_ char *p = NULL;
3911
3912 r = exec_parameters_get_cgroup_path(params, &p);
3913 if (r < 0) {
3914 *exit_status = EXIT_CGROUP;
3915 return log_unit_error_errno(unit, r, "Failed to acquire cgroup path: %m");
3916 }
3917
3918 r = cg_attach_everywhere(params->cgroup_supported, p, 0, NULL, NULL);
3919 if (r < 0) {
3920 *exit_status = EXIT_CGROUP;
3921 return log_unit_error_errno(unit, r, "Failed to attach to cgroup %s: %m", p);
3922 }
3923 }
3924
a8d08f39 3925 if (context->network_namespace_path && runtime && runtime->netns_storage_socket[0] >= 0) {
54c2459d 3926 r = open_shareable_ns_path(runtime->netns_storage_socket, context->network_namespace_path, CLONE_NEWNET);
a8d08f39
LP
3927 if (r < 0) {
3928 *exit_status = EXIT_NETWORK;
3929 return log_unit_error_errno(unit, r, "Failed to open network namespace path %s: %m", context->network_namespace_path);
3930 }
3931 }
3932
a70581ff
XR
3933 if (context->ipc_namespace_path && runtime && runtime->ipcns_storage_socket[0] >= 0) {
3934 r = open_shareable_ns_path(runtime->ipcns_storage_socket, context->ipc_namespace_path, CLONE_NEWIPC);
3935 if (r < 0) {
3936 *exit_status = EXIT_NAMESPACE;
3937 return log_unit_error_errno(unit, r, "Failed to open IPC namespace path %s: %m", context->ipc_namespace_path);
3938 }
3939 }
3940
52c239d7 3941 r = setup_input(context, params, socket_fd, named_iofds);
ff0af2a1
LP
3942 if (r < 0) {
3943 *exit_status = EXIT_STDIN;
12145637 3944 return log_unit_error_errno(unit, r, "Failed to set up standard input: %m");
d35fbf6b 3945 }
034c6ed7 3946
52c239d7 3947 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
3948 if (r < 0) {
3949 *exit_status = EXIT_STDOUT;
12145637 3950 return log_unit_error_errno(unit, r, "Failed to set up standard output: %m");
d35fbf6b
DM
3951 }
3952
52c239d7 3953 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
3954 if (r < 0) {
3955 *exit_status = EXIT_STDERR;
12145637 3956 return log_unit_error_errno(unit, r, "Failed to set up standard error output: %m");
d35fbf6b
DM
3957 }
3958
d35fbf6b 3959 if (context->oom_score_adjust_set) {
9f8168eb
LP
3960 /* When we can't make this change due to EPERM, then let's silently skip over it. User namespaces
3961 * prohibit write access to this file, and we shouldn't trip up over that. */
3962 r = set_oom_score_adjust(context->oom_score_adjust);
065b4774 3963 if (ERRNO_IS_PRIVILEGE(r))
f2341e0a 3964 log_unit_debug_errno(unit, r, "Failed to adjust OOM setting, assuming containerized execution, ignoring: %m");
12145637 3965 else if (r < 0) {
ff0af2a1 3966 *exit_status = EXIT_OOM_ADJUST;
12145637 3967 return log_unit_error_errno(unit, r, "Failed to adjust OOM setting: %m");
613b411c 3968 }
d35fbf6b
DM
3969 }
3970
ad21e542
ZJS
3971 if (context->coredump_filter_set) {
3972 r = set_coredump_filter(context->coredump_filter);
3973 if (ERRNO_IS_PRIVILEGE(r))
3974 log_unit_debug_errno(unit, r, "Failed to adjust coredump_filter, ignoring: %m");
3975 else if (r < 0)
3976 return log_unit_error_errno(unit, r, "Failed to adjust coredump_filter: %m");
3977 }
3978
39090201
DJL
3979 if (context->nice_set) {
3980 r = setpriority_closest(context->nice);
3981 if (r < 0)
3982 return log_unit_error_errno(unit, r, "Failed to set up process scheduling priority (nice level): %m");
3983 }
613b411c 3984
d35fbf6b
DM
3985 if (context->cpu_sched_set) {
3986 struct sched_param param = {
3987 .sched_priority = context->cpu_sched_priority,
3988 };
3989
ff0af2a1
LP
3990 r = sched_setscheduler(0,
3991 context->cpu_sched_policy |
3992 (context->cpu_sched_reset_on_fork ?
3993 SCHED_RESET_ON_FORK : 0),
3994 &param);
3995 if (r < 0) {
3996 *exit_status = EXIT_SETSCHEDULER;
12145637 3997 return log_unit_error_errno(unit, errno, "Failed to set up CPU scheduling: %m");
fc9b2a84 3998 }
d35fbf6b 3999 }
fc9b2a84 4000
e2b2fb7f
MS
4001 if (context->cpu_affinity_from_numa || context->cpu_set.set) {
4002 _cleanup_(cpu_set_reset) CPUSet converted_cpu_set = {};
4003 const CPUSet *cpu_set;
4004
4005 if (context->cpu_affinity_from_numa) {
4006 r = exec_context_cpu_affinity_from_numa(context, &converted_cpu_set);
4007 if (r < 0) {
4008 *exit_status = EXIT_CPUAFFINITY;
4009 return log_unit_error_errno(unit, r, "Failed to derive CPU affinity mask from NUMA mask: %m");
4010 }
4011
4012 cpu_set = &converted_cpu_set;
4013 } else
4014 cpu_set = &context->cpu_set;
4015
4016 if (sched_setaffinity(0, cpu_set->allocated, cpu_set->set) < 0) {
ff0af2a1 4017 *exit_status = EXIT_CPUAFFINITY;
12145637 4018 return log_unit_error_errno(unit, errno, "Failed to set up CPU affinity: %m");
034c6ed7 4019 }
e2b2fb7f 4020 }
034c6ed7 4021
b070c7c0
MS
4022 if (mpol_is_valid(numa_policy_get_type(&context->numa_policy))) {
4023 r = apply_numa_policy(&context->numa_policy);
4024 if (r == -EOPNOTSUPP)
33fe9e3f 4025 log_unit_debug_errno(unit, r, "NUMA support not available, ignoring.");
b070c7c0
MS
4026 else if (r < 0) {
4027 *exit_status = EXIT_NUMA_POLICY;
4028 return log_unit_error_errno(unit, r, "Failed to set NUMA memory policy: %m");
4029 }
4030 }
4031
d35fbf6b
DM
4032 if (context->ioprio_set)
4033 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
ff0af2a1 4034 *exit_status = EXIT_IOPRIO;
12145637 4035 return log_unit_error_errno(unit, errno, "Failed to set up IO scheduling priority: %m");
d35fbf6b 4036 }
da726a4d 4037
d35fbf6b
DM
4038 if (context->timer_slack_nsec != NSEC_INFINITY)
4039 if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
ff0af2a1 4040 *exit_status = EXIT_TIMERSLACK;
12145637 4041 return log_unit_error_errno(unit, errno, "Failed to set up timer slack: %m");
4c2630eb 4042 }
9eba9da4 4043
21022b9d
LP
4044 if (context->personality != PERSONALITY_INVALID) {
4045 r = safe_personality(context->personality);
4046 if (r < 0) {
ff0af2a1 4047 *exit_status = EXIT_PERSONALITY;
12145637 4048 return log_unit_error_errno(unit, r, "Failed to set up execution domain (personality): %m");
4c2630eb 4049 }
21022b9d 4050 }
94f04347 4051
d35fbf6b 4052 if (context->utmp_id)
df0ff127 4053 utmp_put_init_process(context->utmp_id, getpid_cached(), getsid(0),
6a93917d 4054 context->tty_path,
023a4f67
LP
4055 context->utmp_mode == EXEC_UTMP_INIT ? INIT_PROCESS :
4056 context->utmp_mode == EXEC_UTMP_LOGIN ? LOGIN_PROCESS :
4057 USER_PROCESS,
6a93917d 4058 username);
d35fbf6b 4059
08f67696 4060 if (uid_is_valid(uid)) {
ff0af2a1
LP
4061 r = chown_terminal(STDIN_FILENO, uid);
4062 if (r < 0) {
4063 *exit_status = EXIT_STDIN;
12145637 4064 return log_unit_error_errno(unit, r, "Failed to change ownership of terminal: %m");
071830ff 4065 }
d35fbf6b 4066 }
8e274523 4067
4e1dfa45 4068 /* If delegation is enabled we'll pass ownership of the cgroup to the user of the new process. On cgroup v1
62b9bb26 4069 * this is only about systemd's own hierarchy, i.e. not the controller hierarchies, simply because that's not
4e1dfa45 4070 * safe. On cgroup v2 there's only one hierarchy anyway, and delegation is safe there, hence in that case only
62b9bb26 4071 * touch a single hierarchy too. */
584b8688 4072 if (params->cgroup_path && context->user && (params->flags & EXEC_CGROUP_DELEGATE)) {
62b9bb26 4073 r = cg_set_access(SYSTEMD_CGROUP_CONTROLLER, params->cgroup_path, uid, gid);
ff0af2a1
LP
4074 if (r < 0) {
4075 *exit_status = EXIT_CGROUP;
12145637 4076 return log_unit_error_errno(unit, r, "Failed to adjust control group access: %m");
034c6ed7 4077 }
d35fbf6b 4078 }
034c6ed7 4079
5b10116e 4080 for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
8679efde 4081 r = setup_exec_directory(context, params, uid, gid, dt, exit_status);
12145637
LP
4082 if (r < 0)
4083 return log_unit_error_errno(unit, r, "Failed to set up special execution directory in %s: %m", params->prefix[dt]);
d35fbf6b 4084 }
94f04347 4085
bb0c0d6f
LP
4086 if (FLAGS_SET(params->flags, EXEC_WRITE_CREDENTIALS)) {
4087 r = setup_credentials(context, params, unit->id, uid);
4088 if (r < 0) {
4089 *exit_status = EXIT_CREDENTIALS;
4090 return log_unit_error_errno(unit, r, "Failed to set up credentials: %m");
4091 }
4092 }
4093
7bce046b 4094 r = build_environment(
fd63e712 4095 unit,
7bce046b
LP
4096 context,
4097 params,
4098 n_fds,
4099 home,
4100 username,
4101 shell,
4102 journal_stream_dev,
4103 journal_stream_ino,
4104 &our_env);
2065ca69
JW
4105 if (r < 0) {
4106 *exit_status = EXIT_MEMORY;
12145637 4107 return log_oom();
2065ca69
JW
4108 }
4109
4110 r = build_pass_environment(context, &pass_env);
4111 if (r < 0) {
4112 *exit_status = EXIT_MEMORY;
12145637 4113 return log_oom();
2065ca69
JW
4114 }
4115
4116 accum_env = strv_env_merge(5,
4117 params->environment,
4118 our_env,
4119 pass_env,
4120 context->environment,
44e5d006 4121 files_env);
2065ca69
JW
4122 if (!accum_env) {
4123 *exit_status = EXIT_MEMORY;
12145637 4124 return log_oom();
2065ca69 4125 }
1280503b 4126 accum_env = strv_env_clean(accum_env);
2065ca69 4127
096424d1 4128 (void) umask(context->umask);
b213e1c1 4129
b1edf445 4130 r = setup_keyring(unit, context, params, uid, gid);
74dd6b51
LP
4131 if (r < 0) {
4132 *exit_status = EXIT_KEYRING;
12145637 4133 return log_unit_error_errno(unit, r, "Failed to set up kernel keyring: %m");
74dd6b51
LP
4134 }
4135
165a31c0 4136 /* We need sandboxing if the caller asked us to apply it and the command isn't explicitly excepted from it */
1703fa41 4137 needs_sandboxing = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & EXEC_COMMAND_FULLY_PRIVILEGED);
7f18ef0a 4138
165a31c0
LP
4139 /* 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 */
4140 needs_ambient_hack = (params->flags & EXEC_APPLY_SANDBOXING) && (command->flags & EXEC_COMMAND_AMBIENT_MAGIC) && !ambient_capabilities_supported();
7f18ef0a 4141
165a31c0
LP
4142 /* 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 */
4143 if (needs_ambient_hack)
4144 needs_setuid = false;
4145 else
4146 needs_setuid = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & (EXEC_COMMAND_FULLY_PRIVILEGED|EXEC_COMMAND_NO_SETUID));
4147
4148 if (needs_sandboxing) {
7f18ef0a
FK
4149 /* MAC enablement checks need to be done before a new mount ns is created, as they rely on /sys being
4150 * present. The actual MAC context application will happen later, as late as possible, to avoid
4151 * impacting our own code paths. */
4152
349cc4a5 4153#if HAVE_SELINUX
43b1f709 4154 use_selinux = mac_selinux_use();
7f18ef0a 4155#endif
f9fa32f0 4156#if ENABLE_SMACK
43b1f709 4157 use_smack = mac_smack_use();
7f18ef0a 4158#endif
349cc4a5 4159#if HAVE_APPARMOR
43b1f709 4160 use_apparmor = mac_apparmor_use();
7f18ef0a 4161#endif
165a31c0 4162 }
7f18ef0a 4163
ce932d2d
LP
4164 if (needs_sandboxing) {
4165 int which_failed;
4166
4167 /* Let's set the resource limits before we call into PAM, so that pam_limits wins over what
4168 * is set here. (See below.) */
4169
4170 r = setrlimit_closest_all((const struct rlimit* const *) context->rlimit, &which_failed);
4171 if (r < 0) {
4172 *exit_status = EXIT_LIMITS;
4173 return log_unit_error_errno(unit, r, "Failed to adjust resource limit RLIMIT_%s: %m", rlimit_to_string(which_failed));
4174 }
4175 }
4176
0af07108 4177 if (needs_setuid && context->pam_name && username) {
ce932d2d
LP
4178 /* Let's call into PAM after we set up our own idea of resource limits to that pam_limits
4179 * wins here. (See above.) */
4180
1da37e58 4181 /* All fds passed in the fds array will be closed in the pam child process. */
0af07108
ZJS
4182 r = setup_pam(context->pam_name, username, uid, gid, context->tty_path, &accum_env, fds, n_fds);
4183 if (r < 0) {
4184 *exit_status = EXIT_PAM;
4185 return log_unit_error_errno(unit, r, "Failed to set up PAM session: %m");
165a31c0 4186 }
ac45f971 4187
0af07108
ZJS
4188 ngids_after_pam = getgroups_alloc(&gids_after_pam);
4189 if (ngids_after_pam < 0) {
4190 *exit_status = EXIT_MEMORY;
4191 return log_unit_error_errno(unit, ngids_after_pam, "Failed to obtain groups after setting up PAM: %m");
5749f855 4192 }
b213e1c1 4193 }
5749f855 4194
0af07108 4195 if (needs_sandboxing && context->private_users && !have_effective_cap(CAP_SYS_ADMIN)) {
5749f855
AZ
4196 /* If we're unprivileged, set up the user namespace first to enable use of the other namespaces.
4197 * Users with CAP_SYS_ADMIN can set up user namespaces last because they will be able to
4198 * set up the all of the other namespaces (i.e. network, mount, UTS) without a user namespace. */
0af07108
ZJS
4199
4200 userns_set_up = true;
4201 r = setup_private_users(saved_uid, saved_gid, uid, gid);
4202 if (r < 0) {
4203 *exit_status = EXIT_USER;
4204 return log_unit_error_errno(unit, r, "Failed to set up user namespacing for unprivileged user: %m");
5749f855
AZ
4205 }
4206 }
4207
a8d08f39
LP
4208 if ((context->private_network || context->network_namespace_path) && runtime && runtime->netns_storage_socket[0] >= 0) {
4209
6e2d7c4f 4210 if (ns_type_supported(NAMESPACE_NET)) {
54c2459d 4211 r = setup_shareable_ns(runtime->netns_storage_socket, CLONE_NEWNET);
ee00d1e9
ZJS
4212 if (r == -EPERM)
4213 log_unit_warning_errno(unit, r,
4214 "PrivateNetwork=yes is configured, but network namespace setup failed, ignoring: %m");
4215 else if (r < 0) {
6e2d7c4f
MS
4216 *exit_status = EXIT_NETWORK;
4217 return log_unit_error_errno(unit, r, "Failed to set up network namespacing: %m");
4218 }
a8d08f39
LP
4219 } else if (context->network_namespace_path) {
4220 *exit_status = EXIT_NETWORK;
ee00d1e9
ZJS
4221 return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EOPNOTSUPP),
4222 "NetworkNamespacePath= is not supported, refusing.");
6e2d7c4f
MS
4223 } else
4224 log_unit_warning(unit, "PrivateNetwork=yes is configured, but the kernel does not support network namespaces, ignoring.");
d35fbf6b 4225 }
169c1bda 4226
a70581ff
XR
4227 if ((context->private_ipc || context->ipc_namespace_path) && runtime && runtime->ipcns_storage_socket[0] >= 0) {
4228
4229 if (ns_type_supported(NAMESPACE_IPC)) {
4230 r = setup_shareable_ns(runtime->ipcns_storage_socket, CLONE_NEWIPC);
4231 if (r == -EPERM)
4232 log_unit_warning_errno(unit, r,
4233 "PrivateIPC=yes is configured, but IPC namespace setup failed, ignoring: %m");
4234 else if (r < 0) {
4235 *exit_status = EXIT_NAMESPACE;
4236 return log_unit_error_errno(unit, r, "Failed to set up IPC namespacing: %m");
4237 }
4238 } else if (context->ipc_namespace_path) {
4239 *exit_status = EXIT_NAMESPACE;
4240 return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EOPNOTSUPP),
4241 "IPCNamespacePath= is not supported, refusing.");
4242 } else
4243 log_unit_warning(unit, "PrivateIPC=yes is configured, but the kernel does not support IPC namespaces, ignoring.");
4244 }
4245
ee818b89 4246 needs_mount_namespace = exec_needs_mount_namespace(context, params, runtime);
ee818b89 4247 if (needs_mount_namespace) {
7cc5ef5f
ZJS
4248 _cleanup_free_ char *error_path = NULL;
4249
9f71ba8d 4250 r = apply_mount_namespace(unit, command->flags, context, params, runtime, &error_path);
3fbe8dbe
LP
4251 if (r < 0) {
4252 *exit_status = EXIT_NAMESPACE;
7cc5ef5f
ZJS
4253 return log_unit_error_errno(unit, r, "Failed to set up mount namespacing%s%s: %m",
4254 error_path ? ": " : "", strempty(error_path));
3fbe8dbe 4255 }
d35fbf6b 4256 }
81a2b7ce 4257
daf8f72b
LP
4258 if (needs_sandboxing) {
4259 r = apply_protect_hostname(unit, context, exit_status);
4260 if (r < 0)
4261 return r;
aecd5ac6
TM
4262 }
4263
5749f855
AZ
4264 /* Drop groups as early as possible.
4265 * This needs to be done after PrivateDevices=y setup as device nodes should be owned by the host's root.
4266 * For non-root in a userns, devices will be owned by the user/group before the group change, and nobody. */
165a31c0 4267 if (needs_setuid) {
afb11bf1
DG
4268 _cleanup_free_ gid_t *gids_to_enforce = NULL;
4269 int ngids_to_enforce = 0;
4270
4271 ngids_to_enforce = merge_gid_lists(supplementary_gids,
4272 ngids,
4273 gids_after_pam,
4274 ngids_after_pam,
4275 &gids_to_enforce);
4276 if (ngids_to_enforce < 0) {
4277 *exit_status = EXIT_MEMORY;
4278 return log_unit_error_errno(unit,
4279 ngids_to_enforce,
4280 "Failed to merge group lists. Group membership might be incorrect: %m");
4281 }
4282
4283 r = enforce_groups(gid, gids_to_enforce, ngids_to_enforce);
096424d1
LP
4284 if (r < 0) {
4285 *exit_status = EXIT_GROUP;
12145637 4286 return log_unit_error_errno(unit, r, "Changing group credentials failed: %m");
096424d1 4287 }
165a31c0 4288 }
096424d1 4289
5749f855
AZ
4290 /* If the user namespace was not set up above, try to do it now.
4291 * It's preferred to set up the user namespace later (after all other namespaces) so as not to be
4292 * restricted by rules pertaining to combining user namspaces with other namespaces (e.g. in the
4293 * case of mount namespaces being less privileged when the mount point list is copied from a
4294 * different user namespace). */
9008e1ac 4295
5749f855
AZ
4296 if (needs_sandboxing && context->private_users && !userns_set_up) {
4297 r = setup_private_users(saved_uid, saved_gid, uid, gid);
4298 if (r < 0) {
4299 *exit_status = EXIT_USER;
4300 return log_unit_error_errno(unit, r, "Failed to set up user namespacing: %m");
d251207d
LP
4301 }
4302 }
4303
9f71ba8d
ZJS
4304 /* Now that the mount namespace has been set up and privileges adjusted, let's look for the thing we
4305 * shall execute. */
4306
4307 _cleanup_free_ char *executable = NULL;
b83d5050
ZJS
4308 _cleanup_close_ int executable_fd = -1;
4309 r = find_executable_full(command->path, false, &executable, &executable_fd);
9f71ba8d
ZJS
4310 if (r < 0) {
4311 if (r != -ENOMEM && (command->flags & EXEC_COMMAND_IGNORE_FAILURE)) {
4312 log_struct_errno(LOG_INFO, r,
4313 "MESSAGE_ID=" SD_MESSAGE_SPAWN_FAILED_STR,
4314 LOG_UNIT_ID(unit),
4315 LOG_UNIT_INVOCATION_ID(unit),
4316 LOG_UNIT_MESSAGE(unit, "Executable %s missing, skipping: %m",
4317 command->path),
4318 "EXECUTABLE=%s", command->path);
4319 return 0;
4320 }
4321
4322 *exit_status = EXIT_EXEC;
4323 return log_struct_errno(LOG_INFO, r,
4324 "MESSAGE_ID=" SD_MESSAGE_SPAWN_FAILED_STR,
4325 LOG_UNIT_ID(unit),
4326 LOG_UNIT_INVOCATION_ID(unit),
4327 LOG_UNIT_MESSAGE(unit, "Failed to locate executable %s: %m",
4328 command->path),
4329 "EXECUTABLE=%s", command->path);
4330 }
4331
b83d5050
ZJS
4332 r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, executable_fd, &executable_fd);
4333 if (r < 0) {
4334 *exit_status = EXIT_FDS;
4335 return log_unit_error_errno(unit, r, "Failed to shift fd and set FD_CLOEXEC: %m");
4336 }
4337
9f71ba8d
ZJS
4338#if HAVE_SELINUX
4339 if (needs_sandboxing && use_selinux && params->selinux_context_net && socket_fd >= 0) {
4340 r = mac_selinux_get_child_mls_label(socket_fd, executable, context->selinux_context, &mac_selinux_context_net);
4341 if (r < 0) {
4342 *exit_status = EXIT_SELINUX_CONTEXT;
4343 return log_unit_error_errno(unit, r, "Failed to determine SELinux context: %m");
4344 }
4345 }
4346#endif
4347
165a31c0 4348 /* We repeat the fd closing here, to make sure that nothing is leaked from the PAM modules. Note that we are
a70581ff 4349 * 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
4350 * however if we have it as we want to keep it open until the final execve(). */
4351
1da37e58 4352 r = close_all_fds(keep_fds, n_keep_fds);
ff0af2a1
LP
4353 if (r >= 0)
4354 r = shift_fds(fds, n_fds);
4355 if (r >= 0)
25b583d7 4356 r = flags_fds(fds, n_socket_fds, n_storage_fds, context->non_blocking);
ff0af2a1
LP
4357 if (r < 0) {
4358 *exit_status = EXIT_FDS;
12145637 4359 return log_unit_error_errno(unit, r, "Failed to adjust passed file descriptors: %m");
d35fbf6b 4360 }
e66cf1a3 4361
5686391b
LP
4362 /* At this point, the fds we want to pass to the program are all ready and set up, with O_CLOEXEC turned off
4363 * and at the right fd numbers. The are no other fds open, with one exception: the exec_fd if it is defined,
4364 * and it has O_CLOEXEC set, after all we want it to be closed by the execve(), so that our parent knows we
4365 * came this far. */
4366
165a31c0 4367 secure_bits = context->secure_bits;
e66cf1a3 4368
165a31c0
LP
4369 if (needs_sandboxing) {
4370 uint64_t bset;
e66cf1a3 4371
ce932d2d
LP
4372 /* Set the RTPRIO resource limit to 0, but only if nothing else was explicitly
4373 * requested. (Note this is placed after the general resource limit initialization, see
4374 * above, in order to take precedence.) */
f4170c67
LP
4375 if (context->restrict_realtime && !context->rlimit[RLIMIT_RTPRIO]) {
4376 if (setrlimit(RLIMIT_RTPRIO, &RLIMIT_MAKE_CONST(0)) < 0) {
4377 *exit_status = EXIT_LIMITS;
12145637 4378 return log_unit_error_errno(unit, errno, "Failed to adjust RLIMIT_RTPRIO resource limit: %m");
f4170c67
LP
4379 }
4380 }
4381
37ac2744
JB
4382#if ENABLE_SMACK
4383 /* LSM Smack needs the capability CAP_MAC_ADMIN to change the current execution security context of the
4384 * process. This is the latest place before dropping capabilities. Other MAC context are set later. */
4385 if (use_smack) {
b83d5050 4386 r = setup_smack(context, executable_fd);
37ac2744
JB
4387 if (r < 0) {
4388 *exit_status = EXIT_SMACK_PROCESS_LABEL;
4389 return log_unit_error_errno(unit, r, "Failed to set SMACK process label: %m");
4390 }
4391 }
4392#endif
4393
165a31c0
LP
4394 bset = context->capability_bounding_set;
4395 /* If the ambient caps hack is enabled (which means the kernel can't do them, and the user asked for
4396 * our magic fallback), then let's add some extra caps, so that the service can drop privs of its own,
4397 * instead of us doing that */
4398 if (needs_ambient_hack)
4399 bset |= (UINT64_C(1) << CAP_SETPCAP) |
4400 (UINT64_C(1) << CAP_SETUID) |
4401 (UINT64_C(1) << CAP_SETGID);
4402
4403 if (!cap_test_all(bset)) {
4404 r = capability_bounding_set_drop(bset, false);
ff0af2a1
LP
4405 if (r < 0) {
4406 *exit_status = EXIT_CAPABILITIES;
12145637 4407 return log_unit_error_errno(unit, r, "Failed to drop capabilities: %m");
3b8bddde 4408 }
4c2630eb 4409 }
3b8bddde 4410
16fcb191
TK
4411 /* Ambient capabilities are cleared during setresuid() (in enforce_user()) even with
4412 * keep-caps set.
4413 * To be able to raise the ambient capabilities after setresuid() they have to be
4414 * added to the inherited set and keep caps has to be set (done in enforce_user()).
4415 * After setresuid() the ambient capabilities can be raised as they are present in
4416 * the permitted and inhertiable set. However it is possible that someone wants to
4417 * set ambient capabilities without changing the user, so we also set the ambient
4418 * capabilities here.
4419 * The requested ambient capabilities are raised in the inheritable set if the
4420 * second argument is true. */
943800f4 4421 if (!needs_ambient_hack) {
755d4b67
IP
4422 r = capability_ambient_set_apply(context->capability_ambient_set, true);
4423 if (r < 0) {
4424 *exit_status = EXIT_CAPABILITIES;
12145637 4425 return log_unit_error_errno(unit, r, "Failed to apply ambient capabilities (before UID change): %m");
755d4b67 4426 }
755d4b67 4427 }
165a31c0 4428 }
755d4b67 4429
fa97f630
JB
4430 /* chroot to root directory first, before we lose the ability to chroot */
4431 r = apply_root_directory(context, params, needs_mount_namespace, exit_status);
4432 if (r < 0)
4433 return log_unit_error_errno(unit, r, "Chrooting to the requested root directory failed: %m");
4434
165a31c0 4435 if (needs_setuid) {
08f67696 4436 if (uid_is_valid(uid)) {
ff0af2a1
LP
4437 r = enforce_user(context, uid);
4438 if (r < 0) {
4439 *exit_status = EXIT_USER;
12145637 4440 return log_unit_error_errno(unit, r, "Failed to change UID to " UID_FMT ": %m", uid);
5b6319dc 4441 }
165a31c0
LP
4442
4443 if (!needs_ambient_hack &&
4444 context->capability_ambient_set != 0) {
755d4b67 4445
16fcb191 4446 /* Raise the ambient capabilities after user change. */
755d4b67
IP
4447 r = capability_ambient_set_apply(context->capability_ambient_set, false);
4448 if (r < 0) {
4449 *exit_status = EXIT_CAPABILITIES;
12145637 4450 return log_unit_error_errno(unit, r, "Failed to apply ambient capabilities (after UID change): %m");
755d4b67 4451 }
755d4b67 4452 }
5b6319dc 4453 }
165a31c0 4454 }
d35fbf6b 4455
56ef8db9
JB
4456 /* Apply working directory here, because the working directory might be on NFS and only the user running
4457 * this service might have the correct privilege to change to the working directory */
fa97f630 4458 r = apply_working_directory(context, params, home, exit_status);
56ef8db9
JB
4459 if (r < 0)
4460 return log_unit_error_errno(unit, r, "Changing to the requested working directory failed: %m");
4461
165a31c0 4462 if (needs_sandboxing) {
37ac2744 4463 /* Apply other MAC contexts late, but before seccomp syscall filtering, as those should really be last to
5cd9cd35
LP
4464 * influence our own codepaths as little as possible. Moreover, applying MAC contexts usually requires
4465 * syscalls that are subject to seccomp filtering, hence should probably be applied before the syscalls
4466 * are restricted. */
4467
349cc4a5 4468#if HAVE_SELINUX
43b1f709 4469 if (use_selinux) {
5cd9cd35
LP
4470 char *exec_context = mac_selinux_context_net ?: context->selinux_context;
4471
4472 if (exec_context) {
4473 r = setexeccon(exec_context);
4474 if (r < 0) {
4475 *exit_status = EXIT_SELINUX_CONTEXT;
12145637 4476 return log_unit_error_errno(unit, r, "Failed to change SELinux context to %s: %m", exec_context);
5cd9cd35
LP
4477 }
4478 }
4479 }
4480#endif
4481
349cc4a5 4482#if HAVE_APPARMOR
43b1f709 4483 if (use_apparmor && context->apparmor_profile) {
5cd9cd35
LP
4484 r = aa_change_onexec(context->apparmor_profile);
4485 if (r < 0 && !context->apparmor_profile_ignore) {
4486 *exit_status = EXIT_APPARMOR_PROFILE;
12145637 4487 return log_unit_error_errno(unit, errno, "Failed to prepare AppArmor profile change to %s: %m", context->apparmor_profile);
5cd9cd35
LP
4488 }
4489 }
4490#endif
4491
165a31c0 4492 /* PR_GET_SECUREBITS is not privileged, while PR_SET_SECUREBITS is. So to suppress potential EPERMs
dbdc4098
TK
4493 * we'll try not to call PR_SET_SECUREBITS unless necessary. Setting securebits requires
4494 * CAP_SETPCAP. */
4495 if (prctl(PR_GET_SECUREBITS) != secure_bits) {
69e3234d 4496 /* CAP_SETPCAP is required to set securebits. This capability is raised into the
dbdc4098
TK
4497 * effective set here.
4498 * The effective set is overwritten during execve with the following values:
4499 * - ambient set (for non-root processes)
4500 * - (inheritable | bounding) set for root processes)
4501 *
4502 * Hence there is no security impact to raise it in the effective set before execve
4503 */
4504 r = capability_gain_cap_setpcap(NULL);
4505 if (r < 0) {
4506 *exit_status = EXIT_CAPABILITIES;
4507 return log_unit_error_errno(unit, r, "Failed to gain CAP_SETPCAP for setting secure bits");
4508 }
755d4b67 4509 if (prctl(PR_SET_SECUREBITS, secure_bits) < 0) {
ff0af2a1 4510 *exit_status = EXIT_SECUREBITS;
12145637 4511 return log_unit_error_errno(unit, errno, "Failed to set process secure bits: %m");
ff01d048 4512 }
dbdc4098 4513 }
5b6319dc 4514
59eeb84b 4515 if (context_has_no_new_privileges(context))
d35fbf6b 4516 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
ff0af2a1 4517 *exit_status = EXIT_NO_NEW_PRIVILEGES;
12145637 4518 return log_unit_error_errno(unit, errno, "Failed to disable new privileges: %m");
d35fbf6b
DM
4519 }
4520
349cc4a5 4521#if HAVE_SECCOMP
469830d1
LP
4522 r = apply_address_families(unit, context);
4523 if (r < 0) {
4524 *exit_status = EXIT_ADDRESS_FAMILIES;
12145637 4525 return log_unit_error_errno(unit, r, "Failed to restrict address families: %m");
4c2630eb 4526 }
04aa0cb9 4527
469830d1
LP
4528 r = apply_memory_deny_write_execute(unit, context);
4529 if (r < 0) {
4530 *exit_status = EXIT_SECCOMP;
12145637 4531 return log_unit_error_errno(unit, r, "Failed to disable writing to executable memory: %m");
f3e43635 4532 }
f4170c67 4533
469830d1
LP
4534 r = apply_restrict_realtime(unit, context);
4535 if (r < 0) {
4536 *exit_status = EXIT_SECCOMP;
12145637 4537 return log_unit_error_errno(unit, r, "Failed to apply realtime restrictions: %m");
f4170c67
LP
4538 }
4539
f69567cb
LP
4540 r = apply_restrict_suid_sgid(unit, context);
4541 if (r < 0) {
4542 *exit_status = EXIT_SECCOMP;
4543 return log_unit_error_errno(unit, r, "Failed to apply SUID/SGID restrictions: %m");
4544 }
4545
add00535
LP
4546 r = apply_restrict_namespaces(unit, context);
4547 if (r < 0) {
4548 *exit_status = EXIT_SECCOMP;
12145637 4549 return log_unit_error_errno(unit, r, "Failed to apply namespace restrictions: %m");
add00535
LP
4550 }
4551
469830d1
LP
4552 r = apply_protect_sysctl(unit, context);
4553 if (r < 0) {
4554 *exit_status = EXIT_SECCOMP;
12145637 4555 return log_unit_error_errno(unit, r, "Failed to apply sysctl restrictions: %m");
502d704e
DH
4556 }
4557
469830d1
LP
4558 r = apply_protect_kernel_modules(unit, context);
4559 if (r < 0) {
4560 *exit_status = EXIT_SECCOMP;
12145637 4561 return log_unit_error_errno(unit, r, "Failed to apply module loading restrictions: %m");
59eeb84b
LP
4562 }
4563
84703040
KK
4564 r = apply_protect_kernel_logs(unit, context);
4565 if (r < 0) {
4566 *exit_status = EXIT_SECCOMP;
4567 return log_unit_error_errno(unit, r, "Failed to apply kernel log restrictions: %m");
4568 }
4569
fc64760d
KK
4570 r = apply_protect_clock(unit, context);
4571 if (r < 0) {
4572 *exit_status = EXIT_SECCOMP;
4573 return log_unit_error_errno(unit, r, "Failed to apply clock restrictions: %m");
4574 }
4575
469830d1
LP
4576 r = apply_private_devices(unit, context);
4577 if (r < 0) {
4578 *exit_status = EXIT_SECCOMP;
12145637 4579 return log_unit_error_errno(unit, r, "Failed to set up private devices: %m");
469830d1
LP
4580 }
4581
4582 r = apply_syscall_archs(unit, context);
4583 if (r < 0) {
4584 *exit_status = EXIT_SECCOMP;
12145637 4585 return log_unit_error_errno(unit, r, "Failed to apply syscall architecture restrictions: %m");
ba128bb8
LP
4586 }
4587
78e864e5
TM
4588 r = apply_lock_personality(unit, context);
4589 if (r < 0) {
4590 *exit_status = EXIT_SECCOMP;
12145637 4591 return log_unit_error_errno(unit, r, "Failed to lock personalities: %m");
78e864e5
TM
4592 }
4593
9df2cdd8
TM
4594 r = apply_syscall_log(unit, context);
4595 if (r < 0) {
4596 *exit_status = EXIT_SECCOMP;
4597 return log_unit_error_errno(unit, r, "Failed to apply system call log filters: %m");
4598 }
4599
5cd9cd35
LP
4600 /* This really should remain the last step before the execve(), to make sure our own code is unaffected
4601 * by the filter as little as possible. */
165a31c0 4602 r = apply_syscall_filter(unit, context, needs_ambient_hack);
469830d1
LP
4603 if (r < 0) {
4604 *exit_status = EXIT_SECCOMP;
12145637 4605 return log_unit_error_errno(unit, r, "Failed to apply system call filters: %m");
d35fbf6b
DM
4606 }
4607#endif
d35fbf6b 4608 }
034c6ed7 4609
00819cc1
LP
4610 if (!strv_isempty(context->unset_environment)) {
4611 char **ee = NULL;
4612
4613 ee = strv_env_delete(accum_env, 1, context->unset_environment);
4614 if (!ee) {
4615 *exit_status = EXIT_MEMORY;
12145637 4616 return log_oom();
00819cc1
LP
4617 }
4618
130d3d22 4619 strv_free_and_replace(accum_env, ee);
00819cc1
LP
4620 }
4621
7ca69792
AZ
4622 if (!FLAGS_SET(command->flags, EXEC_COMMAND_NO_ENV_EXPAND)) {
4623 replaced_argv = replace_env_argv(command->argv, accum_env);
4624 if (!replaced_argv) {
4625 *exit_status = EXIT_MEMORY;
4626 return log_oom();
4627 }
4628 final_argv = replaced_argv;
4629 } else
4630 final_argv = command->argv;
034c6ed7 4631
f1d34068 4632 if (DEBUG_LOGGING) {
d35fbf6b 4633 _cleanup_free_ char *line;
81a2b7ce 4634
d35fbf6b 4635 line = exec_command_line(final_argv);
a1230ff9 4636 if (line)
f2341e0a 4637 log_struct(LOG_DEBUG,
9f71ba8d 4638 "EXECUTABLE=%s", executable,
f2341e0a 4639 LOG_UNIT_MESSAGE(unit, "Executing: %s", line),
ba360bb0 4640 LOG_UNIT_ID(unit),
a1230ff9 4641 LOG_UNIT_INVOCATION_ID(unit));
d35fbf6b 4642 }
dd305ec9 4643
5686391b
LP
4644 if (exec_fd >= 0) {
4645 uint8_t hot = 1;
4646
4647 /* We have finished with all our initializations. Let's now let the manager know that. From this point
4648 * on, if the manager sees POLLHUP on the exec_fd, then execve() was successful. */
4649
4650 if (write(exec_fd, &hot, sizeof(hot)) < 0) {
4651 *exit_status = EXIT_EXEC;
4652 return log_unit_error_errno(unit, errno, "Failed to enable exec_fd: %m");
4653 }
4654 }
4655
a6d9111c 4656 r = fexecve_or_execve(executable_fd, executable, final_argv, accum_env);
5686391b
LP
4657
4658 if (exec_fd >= 0) {
4659 uint8_t hot = 0;
4660
4661 /* The execve() failed. This means the exec_fd is still open. Which means we need to tell the manager
4662 * that POLLHUP on it no longer means execve() succeeded. */
4663
4664 if (write(exec_fd, &hot, sizeof(hot)) < 0) {
4665 *exit_status = EXIT_EXEC;
4666 return log_unit_error_errno(unit, errno, "Failed to disable exec_fd: %m");
4667 }
4668 }
12145637 4669
ff0af2a1 4670 *exit_status = EXIT_EXEC;
9f71ba8d 4671 return log_unit_error_errno(unit, r, "Failed to execute %s: %m", executable);
d35fbf6b 4672}
81a2b7ce 4673
34cf6c43 4674static int exec_context_load_environment(const Unit *unit, const ExecContext *c, char ***l);
2caa38e9 4675static int exec_context_named_iofds(const ExecContext *c, const ExecParameters *p, int named_iofds[static 3]);
34cf6c43 4676
f2341e0a
LP
4677int exec_spawn(Unit *unit,
4678 ExecCommand *command,
d35fbf6b
DM
4679 const ExecContext *context,
4680 const ExecParameters *params,
4681 ExecRuntime *runtime,
29206d46 4682 DynamicCreds *dcreds,
d35fbf6b 4683 pid_t *ret) {
8351ceae 4684
ee39ca20 4685 int socket_fd, r, named_iofds[3] = { -1, -1, -1 }, *fds = NULL;
78f93209 4686 _cleanup_free_ char *subcgroup_path = NULL;
d35fbf6b 4687 _cleanup_strv_free_ char **files_env = NULL;
da6053d0 4688 size_t n_storage_fds = 0, n_socket_fds = 0;
ff0af2a1 4689 _cleanup_free_ char *line = NULL;
d35fbf6b 4690 pid_t pid;
8351ceae 4691
f2341e0a 4692 assert(unit);
d35fbf6b
DM
4693 assert(command);
4694 assert(context);
4695 assert(ret);
4696 assert(params);
25b583d7 4697 assert(params->fds || (params->n_socket_fds + params->n_storage_fds <= 0));
4298d0b5 4698
d35fbf6b
DM
4699 if (context->std_input == EXEC_INPUT_SOCKET ||
4700 context->std_output == EXEC_OUTPUT_SOCKET ||
4701 context->std_error == EXEC_OUTPUT_SOCKET) {
17df7223 4702
d85ff944
YW
4703 if (params->n_socket_fds > 1)
4704 return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EINVAL), "Got more than one socket.");
eef65bf3 4705
d85ff944
YW
4706 if (params->n_socket_fds == 0)
4707 return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EINVAL), "Got no socket.");
488ab41c 4708
d35fbf6b
DM
4709 socket_fd = params->fds[0];
4710 } else {
4711 socket_fd = -1;
4712 fds = params->fds;
9b141911 4713 n_socket_fds = params->n_socket_fds;
25b583d7 4714 n_storage_fds = params->n_storage_fds;
d35fbf6b 4715 }
94f04347 4716
34cf6c43 4717 r = exec_context_named_iofds(context, params, named_iofds);
52c239d7
LB
4718 if (r < 0)
4719 return log_unit_error_errno(unit, r, "Failed to load a named file descriptor: %m");
4720
f2341e0a 4721 r = exec_context_load_environment(unit, context, &files_env);
ff0af2a1 4722 if (r < 0)
f2341e0a 4723 return log_unit_error_errno(unit, r, "Failed to load environment files: %m");
034c6ed7 4724
ee39ca20 4725 line = exec_command_line(command->argv);
d35fbf6b
DM
4726 if (!line)
4727 return log_oom();
fab56fc5 4728
9f71ba8d
ZJS
4729 /* Fork with up-to-date SELinux label database, so the child inherits the up-to-date db
4730 and, until the next SELinux policy changes, we save further reloads in future children. */
2df2152c
CG
4731 mac_selinux_maybe_reload();
4732
f2341e0a 4733 log_struct(LOG_DEBUG,
9f71ba8d
ZJS
4734 LOG_UNIT_MESSAGE(unit, "About to execute %s", line),
4735 "EXECUTABLE=%s", command->path, /* We won't know the real executable path until we create
4736 the mount namespace in the child, but we want to log
4737 from the parent, so we need to use the (possibly
4738 inaccurate) path here. */
ba360bb0 4739 LOG_UNIT_ID(unit),
a1230ff9 4740 LOG_UNIT_INVOCATION_ID(unit));
12145637 4741
78f93209
LP
4742 if (params->cgroup_path) {
4743 r = exec_parameters_get_cgroup_path(params, &subcgroup_path);
4744 if (r < 0)
4745 return log_unit_error_errno(unit, r, "Failed to acquire subcgroup path: %m");
4746 if (r > 0) { /* We are using a child cgroup */
4747 r = cg_create(SYSTEMD_CGROUP_CONTROLLER, subcgroup_path);
4748 if (r < 0)
4749 return log_unit_error_errno(unit, r, "Failed to create control group '%s': %m", subcgroup_path);
4e806bfa
AZ
4750
4751 /* Normally we would not propagate the oomd xattrs to children but since we created this
4752 * sub-cgroup internally we should do it. */
4753 cgroup_oomd_xattr_apply(unit, subcgroup_path);
78f93209
LP
4754 }
4755 }
4756
d35fbf6b
DM
4757 pid = fork();
4758 if (pid < 0)
74129a12 4759 return log_unit_error_errno(unit, errno, "Failed to fork: %m");
d35fbf6b
DM
4760
4761 if (pid == 0) {
12145637 4762 int exit_status = EXIT_SUCCESS;
ff0af2a1 4763
f2341e0a
LP
4764 r = exec_child(unit,
4765 command,
ff0af2a1
LP
4766 context,
4767 params,
4768 runtime,
29206d46 4769 dcreds,
ff0af2a1 4770 socket_fd,
52c239d7 4771 named_iofds,
4c47affc 4772 fds,
9b141911 4773 n_socket_fds,
25b583d7 4774 n_storage_fds,
ff0af2a1 4775 files_env,
00d9ef85 4776 unit->manager->user_lookup_fds[1],
12145637
LP
4777 &exit_status);
4778
e1714f02
ZJS
4779 if (r < 0) {
4780 const char *status =
4781 exit_status_to_string(exit_status,
e04ed6db 4782 EXIT_STATUS_LIBC | EXIT_STATUS_SYSTEMD);
e1714f02 4783
12145637
LP
4784 log_struct_errno(LOG_ERR, r,
4785 "MESSAGE_ID=" SD_MESSAGE_SPAWN_FAILED_STR,
4786 LOG_UNIT_ID(unit),
4787 LOG_UNIT_INVOCATION_ID(unit),
4788 LOG_UNIT_MESSAGE(unit, "Failed at step %s spawning %s: %m",
e1714f02 4789 status, command->path),
a1230ff9 4790 "EXECUTABLE=%s", command->path);
e1714f02 4791 }
4c2630eb 4792
ff0af2a1 4793 _exit(exit_status);
034c6ed7
LP
4794 }
4795
f2341e0a 4796 log_unit_debug(unit, "Forked %s as "PID_FMT, command->path, pid);
23635a85 4797
78f93209
LP
4798 /* We add the new process to the cgroup both in the child (so that we can be sure that no user code is ever
4799 * executed outside of the cgroup) and in the parent (so that we can be sure that when we kill the cgroup the
4800 * process will be killed too). */
4801 if (subcgroup_path)
4802 (void) cg_attach(SYSTEMD_CGROUP_CONTROLLER, subcgroup_path, pid);
2da3263a 4803
b58b4116 4804 exec_status_start(&command->exec_status, pid);
9fb86720 4805
034c6ed7 4806 *ret = pid;
5cb5a6ff
LP
4807 return 0;
4808}
4809
034c6ed7
LP
4810void exec_context_init(ExecContext *c) {
4811 assert(c);
4812
4c12626c 4813 c->umask = 0022;
9eba9da4 4814 c->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 0);
94f04347 4815 c->cpu_sched_policy = SCHED_OTHER;
071830ff 4816 c->syslog_priority = LOG_DAEMON|LOG_INFO;
74922904 4817 c->syslog_level_prefix = true;
353e12c2 4818 c->ignore_sigpipe = true;
3a43da28 4819 c->timer_slack_nsec = NSEC_INFINITY;
050f7277 4820 c->personality = PERSONALITY_INVALID;
5b10116e
ZJS
4821 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++)
4822 c->directories[t].mode = 0755;
12213aed 4823 c->timeout_clean_usec = USEC_INFINITY;
a103496c 4824 c->capability_bounding_set = CAP_ALL;
aa9d574d
YW
4825 assert_cc(NAMESPACE_FLAGS_INITIAL != NAMESPACE_FLAGS_ALL);
4826 c->restrict_namespaces = NAMESPACE_FLAGS_INITIAL;
d3070fbd 4827 c->log_level_max = -1;
005bfaf1
TM
4828#if HAVE_SECCOMP
4829 c->syscall_errno = SECCOMP_ERROR_NUMBER_KILL;
4830#endif
b070c7c0 4831 numa_policy_reset(&c->numa_policy);
034c6ed7
LP
4832}
4833
613b411c 4834void exec_context_done(ExecContext *c) {
5cb5a6ff
LP
4835 assert(c);
4836
6796073e
LP
4837 c->environment = strv_free(c->environment);
4838 c->environment_files = strv_free(c->environment_files);
b4c14404 4839 c->pass_environment = strv_free(c->pass_environment);
00819cc1 4840 c->unset_environment = strv_free(c->unset_environment);
8c7be95e 4841
31ce987c 4842 rlimit_free_all(c->rlimit);
034c6ed7 4843
5b10116e 4844 for (size_t l = 0; l < 3; l++) {
52c239d7 4845 c->stdio_fdname[l] = mfree(c->stdio_fdname[l]);
2038c3f5
LP
4846 c->stdio_file[l] = mfree(c->stdio_file[l]);
4847 }
52c239d7 4848
a1e58e8e
LP
4849 c->working_directory = mfree(c->working_directory);
4850 c->root_directory = mfree(c->root_directory);
915e6d16 4851 c->root_image = mfree(c->root_image);
18d73705 4852 c->root_image_options = mount_options_free_all(c->root_image_options);
0389f4fa
LB
4853 c->root_hash = mfree(c->root_hash);
4854 c->root_hash_size = 0;
4855 c->root_hash_path = mfree(c->root_hash_path);
d4d55b0d
LB
4856 c->root_hash_sig = mfree(c->root_hash_sig);
4857 c->root_hash_sig_size = 0;
4858 c->root_hash_sig_path = mfree(c->root_hash_sig_path);
0389f4fa 4859 c->root_verity = mfree(c->root_verity);
93f59701 4860 c->extension_images = mount_image_free_many(c->extension_images, &c->n_extension_images);
a1e58e8e
LP
4861 c->tty_path = mfree(c->tty_path);
4862 c->syslog_identifier = mfree(c->syslog_identifier);
4863 c->user = mfree(c->user);
4864 c->group = mfree(c->group);
034c6ed7 4865
6796073e 4866 c->supplementary_groups = strv_free(c->supplementary_groups);
94f04347 4867
a1e58e8e 4868 c->pam_name = mfree(c->pam_name);
5b6319dc 4869
2a624c36
AP
4870 c->read_only_paths = strv_free(c->read_only_paths);
4871 c->read_write_paths = strv_free(c->read_write_paths);
4872 c->inaccessible_paths = strv_free(c->inaccessible_paths);
ddc155b2
TM
4873 c->exec_paths = strv_free(c->exec_paths);
4874 c->no_exec_paths = strv_free(c->no_exec_paths);
82c121a4 4875
d2d6c096 4876 bind_mount_free_many(c->bind_mounts, c->n_bind_mounts);
8e06d57c
YW
4877 c->bind_mounts = NULL;
4878 c->n_bind_mounts = 0;
2abd4e38
YW
4879 temporary_filesystem_free_many(c->temporary_filesystems, c->n_temporary_filesystems);
4880 c->temporary_filesystems = NULL;
4881 c->n_temporary_filesystems = 0;
b3d13314 4882 c->mount_images = mount_image_free_many(c->mount_images, &c->n_mount_images);
d2d6c096 4883
0985c7c4 4884 cpu_set_reset(&c->cpu_set);
b070c7c0 4885 numa_policy_reset(&c->numa_policy);
86a3475b 4886
a1e58e8e
LP
4887 c->utmp_id = mfree(c->utmp_id);
4888 c->selinux_context = mfree(c->selinux_context);
4889 c->apparmor_profile = mfree(c->apparmor_profile);
5b8e1b77 4890 c->smack_process_label = mfree(c->smack_process_label);
eef65bf3 4891
8cfa775f 4892 c->syscall_filter = hashmap_free(c->syscall_filter);
525d3cc7
LP
4893 c->syscall_archs = set_free(c->syscall_archs);
4894 c->address_families = set_free(c->address_families);
e66cf1a3 4895
5b10116e
ZJS
4896 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++)
4897 c->directories[t].paths = strv_free(c->directories[t].paths);
d3070fbd
LP
4898
4899 c->log_level_max = -1;
4900
4901 exec_context_free_log_extra_fields(c);
08f3be7a 4902
5ac1530e
ZJS
4903 c->log_ratelimit_interval_usec = 0;
4904 c->log_ratelimit_burst = 0;
90fc172e 4905
08f3be7a
LP
4906 c->stdin_data = mfree(c->stdin_data);
4907 c->stdin_data_size = 0;
a8d08f39
LP
4908
4909 c->network_namespace_path = mfree(c->network_namespace_path);
91dd5f7c
LP
4910
4911 c->log_namespace = mfree(c->log_namespace);
bb0c0d6f
LP
4912
4913 c->load_credentials = strv_free(c->load_credentials);
4914 c->set_credentials = hashmap_free(c->set_credentials);
e66cf1a3
LP
4915}
4916
34cf6c43 4917int exec_context_destroy_runtime_directory(const ExecContext *c, const char *runtime_prefix) {
e66cf1a3
LP
4918 char **i;
4919
4920 assert(c);
4921
4922 if (!runtime_prefix)
4923 return 0;
4924
3536f49e 4925 STRV_FOREACH(i, c->directories[EXEC_DIRECTORY_RUNTIME].paths) {
e66cf1a3
LP
4926 _cleanup_free_ char *p;
4927
494d0247
YW
4928 if (exec_directory_is_private(c, EXEC_DIRECTORY_RUNTIME))
4929 p = path_join(runtime_prefix, "private", *i);
4930 else
4931 p = path_join(runtime_prefix, *i);
e66cf1a3
LP
4932 if (!p)
4933 return -ENOMEM;
4934
7bc4bf4a
LP
4935 /* We execute this synchronously, since we need to be sure this is gone when we start the
4936 * service next. */
c6878637 4937 (void) rm_rf(p, REMOVE_ROOT);
e66cf1a3
LP
4938 }
4939
4940 return 0;
5cb5a6ff
LP
4941}
4942
bb0c0d6f
LP
4943int exec_context_destroy_credentials(const ExecContext *c, const char *runtime_prefix, const char *unit) {
4944 _cleanup_free_ char *p = NULL;
4945
4946 assert(c);
4947
4948 if (!runtime_prefix || !unit)
4949 return 0;
4950
4951 p = path_join(runtime_prefix, "credentials", unit);
4952 if (!p)
4953 return -ENOMEM;
4954
4955 /* This is either a tmpfs/ramfs of its own, or a plain directory. Either way, let's first try to
4956 * unmount it, and afterwards remove the mount point */
4957 (void) umount2(p, MNT_DETACH|UMOUNT_NOFOLLOW);
4958 (void) rm_rf(p, REMOVE_ROOT|REMOVE_CHMOD);
4959
4960 return 0;
4961}
4962
34cf6c43 4963static void exec_command_done(ExecCommand *c) {
43d0fcbd
LP
4964 assert(c);
4965
a1e58e8e 4966 c->path = mfree(c->path);
6796073e 4967 c->argv = strv_free(c->argv);
43d0fcbd
LP
4968}
4969
da6053d0 4970void exec_command_done_array(ExecCommand *c, size_t n) {
fe96c0f8 4971 for (size_t i = 0; i < n; i++)
43d0fcbd
LP
4972 exec_command_done(c+i);
4973}
4974
f1acf85a 4975ExecCommand* exec_command_free_list(ExecCommand *c) {
5cb5a6ff
LP
4976 ExecCommand *i;
4977
4978 while ((i = c)) {
71fda00f 4979 LIST_REMOVE(command, c, i);
43d0fcbd 4980 exec_command_done(i);
5cb5a6ff
LP
4981 free(i);
4982 }
f1acf85a
ZJS
4983
4984 return NULL;
5cb5a6ff
LP
4985}
4986
da6053d0 4987void exec_command_free_array(ExecCommand **c, size_t n) {
5b10116e 4988 for (size_t i = 0; i < n; i++)
f1acf85a 4989 c[i] = exec_command_free_list(c[i]);
034c6ed7
LP
4990}
4991
6a1d4d9f 4992void exec_command_reset_status_array(ExecCommand *c, size_t n) {
5b10116e 4993 for (size_t i = 0; i < n; i++)
6a1d4d9f
LP
4994 exec_status_reset(&c[i].exec_status);
4995}
4996
4997void exec_command_reset_status_list_array(ExecCommand **c, size_t n) {
5b10116e 4998 for (size_t i = 0; i < n; i++) {
6a1d4d9f
LP
4999 ExecCommand *z;
5000
5001 LIST_FOREACH(command, z, c[i])
5002 exec_status_reset(&z->exec_status);
5003 }
5004}
5005
039f0e70 5006typedef struct InvalidEnvInfo {
34cf6c43 5007 const Unit *unit;
039f0e70
LP
5008 const char *path;
5009} InvalidEnvInfo;
5010
5011static void invalid_env(const char *p, void *userdata) {
5012 InvalidEnvInfo *info = userdata;
5013
f2341e0a 5014 log_unit_error(info->unit, "Ignoring invalid environment assignment '%s': %s", p, info->path);
039f0e70
LP
5015}
5016
52c239d7
LB
5017const char* exec_context_fdname(const ExecContext *c, int fd_index) {
5018 assert(c);
5019
5020 switch (fd_index) {
5073ff6b 5021
52c239d7
LB
5022 case STDIN_FILENO:
5023 if (c->std_input != EXEC_INPUT_NAMED_FD)
5024 return NULL;
5073ff6b 5025
52c239d7 5026 return c->stdio_fdname[STDIN_FILENO] ?: "stdin";
5073ff6b 5027
52c239d7
LB
5028 case STDOUT_FILENO:
5029 if (c->std_output != EXEC_OUTPUT_NAMED_FD)
5030 return NULL;
5073ff6b 5031
52c239d7 5032 return c->stdio_fdname[STDOUT_FILENO] ?: "stdout";
5073ff6b 5033
52c239d7
LB
5034 case STDERR_FILENO:
5035 if (c->std_error != EXEC_OUTPUT_NAMED_FD)
5036 return NULL;
5073ff6b 5037
52c239d7 5038 return c->stdio_fdname[STDERR_FILENO] ?: "stderr";
5073ff6b 5039
52c239d7
LB
5040 default:
5041 return NULL;
5042 }
5043}
5044
2caa38e9
LP
5045static int exec_context_named_iofds(
5046 const ExecContext *c,
5047 const ExecParameters *p,
5048 int named_iofds[static 3]) {
5049
5b10116e 5050 size_t targets;
56fbd561 5051 const char* stdio_fdname[3];
da6053d0 5052 size_t n_fds;
52c239d7
LB
5053
5054 assert(c);
5055 assert(p);
2caa38e9 5056 assert(named_iofds);
52c239d7
LB
5057
5058 targets = (c->std_input == EXEC_INPUT_NAMED_FD) +
5059 (c->std_output == EXEC_OUTPUT_NAMED_FD) +
5060 (c->std_error == EXEC_OUTPUT_NAMED_FD);
5061
5b10116e 5062 for (size_t i = 0; i < 3; i++)
52c239d7
LB
5063 stdio_fdname[i] = exec_context_fdname(c, i);
5064
4c47affc
FB
5065 n_fds = p->n_storage_fds + p->n_socket_fds;
5066
5b10116e 5067 for (size_t i = 0; i < n_fds && targets > 0; i++)
56fbd561
ZJS
5068 if (named_iofds[STDIN_FILENO] < 0 &&
5069 c->std_input == EXEC_INPUT_NAMED_FD &&
5070 stdio_fdname[STDIN_FILENO] &&
5071 streq(p->fd_names[i], stdio_fdname[STDIN_FILENO])) {
5072
52c239d7
LB
5073 named_iofds[STDIN_FILENO] = p->fds[i];
5074 targets--;
56fbd561
ZJS
5075
5076 } else if (named_iofds[STDOUT_FILENO] < 0 &&
5077 c->std_output == EXEC_OUTPUT_NAMED_FD &&
5078 stdio_fdname[STDOUT_FILENO] &&
5079 streq(p->fd_names[i], stdio_fdname[STDOUT_FILENO])) {
5080
52c239d7
LB
5081 named_iofds[STDOUT_FILENO] = p->fds[i];
5082 targets--;
56fbd561
ZJS
5083
5084 } else if (named_iofds[STDERR_FILENO] < 0 &&
5085 c->std_error == EXEC_OUTPUT_NAMED_FD &&
5086 stdio_fdname[STDERR_FILENO] &&
5087 streq(p->fd_names[i], stdio_fdname[STDERR_FILENO])) {
5088
52c239d7
LB
5089 named_iofds[STDERR_FILENO] = p->fds[i];
5090 targets--;
5091 }
5092
56fbd561 5093 return targets == 0 ? 0 : -ENOENT;
52c239d7
LB
5094}
5095
34cf6c43 5096static int exec_context_load_environment(const Unit *unit, const ExecContext *c, char ***l) {
8c7be95e
LP
5097 char **i, **r = NULL;
5098
5099 assert(c);
5100 assert(l);
5101
5102 STRV_FOREACH(i, c->environment_files) {
5103 char *fn;
52511fae 5104 int k;
8c7be95e
LP
5105 bool ignore = false;
5106 char **p;
7fd1b19b 5107 _cleanup_globfree_ glob_t pglob = {};
8c7be95e
LP
5108
5109 fn = *i;
5110
5111 if (fn[0] == '-') {
5112 ignore = true;
313cefa1 5113 fn++;
8c7be95e
LP
5114 }
5115
5116 if (!path_is_absolute(fn)) {
8c7be95e
LP
5117 if (ignore)
5118 continue;
5119
5120 strv_free(r);
5121 return -EINVAL;
5122 }
5123
2bef10ab 5124 /* Filename supports globbing, take all matching files */
d8c92e8b
ZJS
5125 k = safe_glob(fn, 0, &pglob);
5126 if (k < 0) {
2bef10ab
PL
5127 if (ignore)
5128 continue;
8c7be95e 5129
2bef10ab 5130 strv_free(r);
d8c92e8b 5131 return k;
2bef10ab 5132 }
8c7be95e 5133
d8c92e8b
ZJS
5134 /* When we don't match anything, -ENOENT should be returned */
5135 assert(pglob.gl_pathc > 0);
5136
5b10116e 5137 for (unsigned n = 0; n < pglob.gl_pathc; n++) {
aa8fbc74 5138 k = load_env_file(NULL, pglob.gl_pathv[n], &p);
2bef10ab
PL
5139 if (k < 0) {
5140 if (ignore)
5141 continue;
8c7be95e 5142
2bef10ab 5143 strv_free(r);
2bef10ab 5144 return k;
e9c1ea9d 5145 }
ebc05a09 5146 /* Log invalid environment variables with filename */
039f0e70
LP
5147 if (p) {
5148 InvalidEnvInfo info = {
f2341e0a 5149 .unit = unit,
039f0e70
LP
5150 .path = pglob.gl_pathv[n]
5151 };
5152
5153 p = strv_env_clean_with_callback(p, invalid_env, &info);
5154 }
8c7be95e 5155
234519ae 5156 if (!r)
2bef10ab
PL
5157 r = p;
5158 else {
5159 char **m;
8c7be95e 5160
2bef10ab
PL
5161 m = strv_env_merge(2, r, p);
5162 strv_free(r);
5163 strv_free(p);
c84a9488 5164 if (!m)
2bef10ab 5165 return -ENOMEM;
2bef10ab
PL
5166
5167 r = m;
5168 }
8c7be95e
LP
5169 }
5170 }
5171
5172 *l = r;
5173
5174 return 0;
5175}
5176
6ac8fdc9 5177static bool tty_may_match_dev_console(const char *tty) {
7b912648 5178 _cleanup_free_ char *resolved = NULL;
6ac8fdc9 5179
1e22b5cd
LP
5180 if (!tty)
5181 return true;
5182
a119ec7c 5183 tty = skip_dev_prefix(tty);
6ac8fdc9
MS
5184
5185 /* trivial identity? */
5186 if (streq(tty, "console"))
5187 return true;
5188
7b912648
LP
5189 if (resolve_dev_console(&resolved) < 0)
5190 return true; /* if we could not resolve, assume it may */
6ac8fdc9
MS
5191
5192 /* "tty0" means the active VC, so it may be the same sometimes */
955f1c85 5193 return path_equal(resolved, tty) || (streq(resolved, "tty0") && tty_is_vc(tty));
6ac8fdc9
MS
5194}
5195
6c0ae739
LP
5196static bool exec_context_may_touch_tty(const ExecContext *ec) {
5197 assert(ec);
1e22b5cd 5198
6c0ae739 5199 return ec->tty_reset ||
1e22b5cd
LP
5200 ec->tty_vhangup ||
5201 ec->tty_vt_disallocate ||
6ac8fdc9
MS
5202 is_terminal_input(ec->std_input) ||
5203 is_terminal_output(ec->std_output) ||
6c0ae739
LP
5204 is_terminal_output(ec->std_error);
5205}
5206
5207bool exec_context_may_touch_console(const ExecContext *ec) {
5208
5209 return exec_context_may_touch_tty(ec) &&
1e22b5cd 5210 tty_may_match_dev_console(exec_context_tty_path(ec));
6ac8fdc9
MS
5211}
5212
15ae422b
LP
5213static void strv_fprintf(FILE *f, char **l) {
5214 char **g;
5215
5216 assert(f);
5217
5218 STRV_FOREACH(g, l)
5219 fprintf(f, " %s", *g);
5220}
5221
ddc155b2
TM
5222static void strv_dump(FILE* f, const char *prefix, const char *name, char **strv) {
5223 assert(f);
5224 assert(prefix);
5225 assert(name);
5226
5227 if (!strv_isempty(strv)) {
5228 fprintf(f, "%s%s:", name, prefix);
5229 strv_fprintf(f, strv);
5230 fputs("\n", f);
5231 }
5232}
5233
34cf6c43 5234void exec_context_dump(const ExecContext *c, FILE* f, const char *prefix) {
12213aed 5235 char **e, **d, buf_clean[FORMAT_TIMESPAN_MAX];
add00535 5236 int r;
9eba9da4 5237
5cb5a6ff
LP
5238 assert(c);
5239 assert(f);
5240
4ad49000 5241 prefix = strempty(prefix);
5cb5a6ff
LP
5242
5243 fprintf(f,
94f04347
LP
5244 "%sUMask: %04o\n"
5245 "%sWorkingDirectory: %s\n"
451a074f 5246 "%sRootDirectory: %s\n"
15ae422b 5247 "%sNonBlocking: %s\n"
64747e2d 5248 "%sPrivateTmp: %s\n"
7f112f50 5249 "%sPrivateDevices: %s\n"
59eeb84b 5250 "%sProtectKernelTunables: %s\n"
e66a2f65 5251 "%sProtectKernelModules: %s\n"
84703040 5252 "%sProtectKernelLogs: %s\n"
fc64760d 5253 "%sProtectClock: %s\n"
59eeb84b 5254 "%sProtectControlGroups: %s\n"
d251207d
LP
5255 "%sPrivateNetwork: %s\n"
5256 "%sPrivateUsers: %s\n"
1b8689f9
LP
5257 "%sProtectHome: %s\n"
5258 "%sProtectSystem: %s\n"
5d997827 5259 "%sMountAPIVFS: %s\n"
f3e43635 5260 "%sIgnoreSIGPIPE: %s\n"
f4170c67 5261 "%sMemoryDenyWriteExecute: %s\n"
b1edf445 5262 "%sRestrictRealtime: %s\n"
f69567cb 5263 "%sRestrictSUIDSGID: %s\n"
aecd5ac6 5264 "%sKeyringMode: %s\n"
4e399953
LP
5265 "%sProtectHostname: %s\n"
5266 "%sProtectProc: %s\n"
5267 "%sProcSubset: %s\n",
5cb5a6ff 5268 prefix, c->umask,
14eb3285
LP
5269 prefix, empty_to_root(c->working_directory),
5270 prefix, empty_to_root(c->root_directory),
15ae422b 5271 prefix, yes_no(c->non_blocking),
64747e2d 5272 prefix, yes_no(c->private_tmp),
7f112f50 5273 prefix, yes_no(c->private_devices),
59eeb84b 5274 prefix, yes_no(c->protect_kernel_tunables),
e66a2f65 5275 prefix, yes_no(c->protect_kernel_modules),
84703040 5276 prefix, yes_no(c->protect_kernel_logs),
fc64760d 5277 prefix, yes_no(c->protect_clock),
59eeb84b 5278 prefix, yes_no(c->protect_control_groups),
d251207d
LP
5279 prefix, yes_no(c->private_network),
5280 prefix, yes_no(c->private_users),
1b8689f9
LP
5281 prefix, protect_home_to_string(c->protect_home),
5282 prefix, protect_system_to_string(c->protect_system),
5e98086d 5283 prefix, yes_no(exec_context_get_effective_mount_apivfs(c)),
f3e43635 5284 prefix, yes_no(c->ignore_sigpipe),
f4170c67 5285 prefix, yes_no(c->memory_deny_write_execute),
b1edf445 5286 prefix, yes_no(c->restrict_realtime),
f69567cb 5287 prefix, yes_no(c->restrict_suid_sgid),
aecd5ac6 5288 prefix, exec_keyring_mode_to_string(c->keyring_mode),
4e399953
LP
5289 prefix, yes_no(c->protect_hostname),
5290 prefix, protect_proc_to_string(c->protect_proc),
5291 prefix, proc_subset_to_string(c->proc_subset));
fb33a393 5292
915e6d16
LP
5293 if (c->root_image)
5294 fprintf(f, "%sRootImage: %s\n", prefix, c->root_image);
5295
18d73705
LB
5296 if (c->root_image_options) {
5297 MountOptions *o;
5298
5299 fprintf(f, "%sRootImageOptions:", prefix);
5300 LIST_FOREACH(mount_options, o, c->root_image_options)
5301 if (!isempty(o->options))
9ece6444
LB
5302 fprintf(f, " %s:%s",
5303 partition_designator_to_string(o->partition_designator),
5304 o->options);
18d73705
LB
5305 fprintf(f, "\n");
5306 }
5307
0389f4fa
LB
5308 if (c->root_hash) {
5309 _cleanup_free_ char *encoded = NULL;
5310 encoded = hexmem(c->root_hash, c->root_hash_size);
5311 if (encoded)
5312 fprintf(f, "%sRootHash: %s\n", prefix, encoded);
5313 }
5314
5315 if (c->root_hash_path)
5316 fprintf(f, "%sRootHash: %s\n", prefix, c->root_hash_path);
5317
d4d55b0d
LB
5318 if (c->root_hash_sig) {
5319 _cleanup_free_ char *encoded = NULL;
5320 ssize_t len;
5321 len = base64mem(c->root_hash_sig, c->root_hash_sig_size, &encoded);
5322 if (len)
5323 fprintf(f, "%sRootHashSignature: base64:%s\n", prefix, encoded);
5324 }
5325
5326 if (c->root_hash_sig_path)
5327 fprintf(f, "%sRootHashSignature: %s\n", prefix, c->root_hash_sig_path);
5328
0389f4fa
LB
5329 if (c->root_verity)
5330 fprintf(f, "%sRootVerity: %s\n", prefix, c->root_verity);
5331
8c7be95e
LP
5332 STRV_FOREACH(e, c->environment)
5333 fprintf(f, "%sEnvironment: %s\n", prefix, *e);
5334
5335 STRV_FOREACH(e, c->environment_files)
5336 fprintf(f, "%sEnvironmentFile: %s\n", prefix, *e);
94f04347 5337
b4c14404
FB
5338 STRV_FOREACH(e, c->pass_environment)
5339 fprintf(f, "%sPassEnvironment: %s\n", prefix, *e);
5340
00819cc1
LP
5341 STRV_FOREACH(e, c->unset_environment)
5342 fprintf(f, "%sUnsetEnvironment: %s\n", prefix, *e);
5343
53f47dfc
YW
5344 fprintf(f, "%sRuntimeDirectoryPreserve: %s\n", prefix, exec_preserve_mode_to_string(c->runtime_directory_preserve_mode));
5345
5b10116e 5346 for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
3536f49e
YW
5347 fprintf(f, "%s%sMode: %04o\n", prefix, exec_directory_type_to_string(dt), c->directories[dt].mode);
5348
5349 STRV_FOREACH(d, c->directories[dt].paths)
5350 fprintf(f, "%s%s: %s\n", prefix, exec_directory_type_to_string(dt), *d);
5351 }
c2bbd90b 5352
12213aed
YW
5353 fprintf(f,
5354 "%sTimeoutCleanSec: %s\n",
5355 prefix, format_timespan(buf_clean, sizeof(buf_clean), c->timeout_clean_usec, USEC_PER_SEC));
5356
fb33a393
LP
5357 if (c->nice_set)
5358 fprintf(f,
5359 "%sNice: %i\n",
5360 prefix, c->nice);
5361
dd6c17b1 5362 if (c->oom_score_adjust_set)
fb33a393 5363 fprintf(f,
dd6c17b1
LP
5364 "%sOOMScoreAdjust: %i\n",
5365 prefix, c->oom_score_adjust);
9eba9da4 5366
ad21e542
ZJS
5367 if (c->coredump_filter_set)
5368 fprintf(f,
5369 "%sCoredumpFilter: 0x%"PRIx64"\n",
5370 prefix, c->coredump_filter);
5371
5b10116e 5372 for (unsigned i = 0; i < RLIM_NLIMITS; i++)
3c11da9d 5373 if (c->rlimit[i]) {
4c3a2b84 5374 fprintf(f, "%sLimit%s: " RLIM_FMT "\n",
3c11da9d 5375 prefix, rlimit_to_string(i), c->rlimit[i]->rlim_max);
4c3a2b84 5376 fprintf(f, "%sLimit%sSoft: " RLIM_FMT "\n",
3c11da9d
EV
5377 prefix, rlimit_to_string(i), c->rlimit[i]->rlim_cur);
5378 }
94f04347 5379
f8b69d1d 5380 if (c->ioprio_set) {
1756a011 5381 _cleanup_free_ char *class_str = NULL;
f8b69d1d 5382
837df140
YW
5383 r = ioprio_class_to_string_alloc(IOPRIO_PRIO_CLASS(c->ioprio), &class_str);
5384 if (r >= 0)
5385 fprintf(f, "%sIOSchedulingClass: %s\n", prefix, class_str);
5386
5387 fprintf(f, "%sIOPriority: %lu\n", prefix, IOPRIO_PRIO_DATA(c->ioprio));
f8b69d1d 5388 }
94f04347 5389
f8b69d1d 5390 if (c->cpu_sched_set) {
1756a011 5391 _cleanup_free_ char *policy_str = NULL;
f8b69d1d 5392
837df140
YW
5393 r = sched_policy_to_string_alloc(c->cpu_sched_policy, &policy_str);
5394 if (r >= 0)
5395 fprintf(f, "%sCPUSchedulingPolicy: %s\n", prefix, policy_str);
5396
94f04347 5397 fprintf(f,
38b48754
LP
5398 "%sCPUSchedulingPriority: %i\n"
5399 "%sCPUSchedulingResetOnFork: %s\n",
38b48754
LP
5400 prefix, c->cpu_sched_priority,
5401 prefix, yes_no(c->cpu_sched_reset_on_fork));
b929bf04 5402 }
94f04347 5403
0985c7c4 5404 if (c->cpu_set.set) {
e7fca352
MS
5405 _cleanup_free_ char *affinity = NULL;
5406
5407 affinity = cpu_set_to_range_string(&c->cpu_set);
5408 fprintf(f, "%sCPUAffinity: %s\n", prefix, affinity);
94f04347
LP
5409 }
5410
b070c7c0
MS
5411 if (mpol_is_valid(numa_policy_get_type(&c->numa_policy))) {
5412 _cleanup_free_ char *nodes = NULL;
5413
5414 nodes = cpu_set_to_range_string(&c->numa_policy.nodes);
5415 fprintf(f, "%sNUMAPolicy: %s\n", prefix, mpol_to_string(numa_policy_get_type(&c->numa_policy)));
5416 fprintf(f, "%sNUMAMask: %s\n", prefix, strnull(nodes));
5417 }
5418
3a43da28 5419 if (c->timer_slack_nsec != NSEC_INFINITY)
ccd06097 5420 fprintf(f, "%sTimerSlackNSec: "NSEC_FMT "\n", prefix, c->timer_slack_nsec);
94f04347
LP
5421
5422 fprintf(f,
80876c20
LP
5423 "%sStandardInput: %s\n"
5424 "%sStandardOutput: %s\n"
5425 "%sStandardError: %s\n",
5426 prefix, exec_input_to_string(c->std_input),
5427 prefix, exec_output_to_string(c->std_output),
5428 prefix, exec_output_to_string(c->std_error));
5429
befc4a80
LP
5430 if (c->std_input == EXEC_INPUT_NAMED_FD)
5431 fprintf(f, "%sStandardInputFileDescriptorName: %s\n", prefix, c->stdio_fdname[STDIN_FILENO]);
5432 if (c->std_output == EXEC_OUTPUT_NAMED_FD)
5433 fprintf(f, "%sStandardOutputFileDescriptorName: %s\n", prefix, c->stdio_fdname[STDOUT_FILENO]);
5434 if (c->std_error == EXEC_OUTPUT_NAMED_FD)
5435 fprintf(f, "%sStandardErrorFileDescriptorName: %s\n", prefix, c->stdio_fdname[STDERR_FILENO]);
5436
5437 if (c->std_input == EXEC_INPUT_FILE)
5438 fprintf(f, "%sStandardInputFile: %s\n", prefix, c->stdio_file[STDIN_FILENO]);
5439 if (c->std_output == EXEC_OUTPUT_FILE)
5440 fprintf(f, "%sStandardOutputFile: %s\n", prefix, c->stdio_file[STDOUT_FILENO]);
566b7d23
ZD
5441 if (c->std_output == EXEC_OUTPUT_FILE_APPEND)
5442 fprintf(f, "%sStandardOutputFileToAppend: %s\n", prefix, c->stdio_file[STDOUT_FILENO]);
8d7dab1f
LW
5443 if (c->std_output == EXEC_OUTPUT_FILE_TRUNCATE)
5444 fprintf(f, "%sStandardOutputFileToTruncate: %s\n", prefix, c->stdio_file[STDOUT_FILENO]);
befc4a80
LP
5445 if (c->std_error == EXEC_OUTPUT_FILE)
5446 fprintf(f, "%sStandardErrorFile: %s\n", prefix, c->stdio_file[STDERR_FILENO]);
566b7d23
ZD
5447 if (c->std_error == EXEC_OUTPUT_FILE_APPEND)
5448 fprintf(f, "%sStandardErrorFileToAppend: %s\n", prefix, c->stdio_file[STDERR_FILENO]);
8d7dab1f
LW
5449 if (c->std_error == EXEC_OUTPUT_FILE_TRUNCATE)
5450 fprintf(f, "%sStandardErrorFileToTruncate: %s\n", prefix, c->stdio_file[STDERR_FILENO]);
befc4a80 5451
80876c20
LP
5452 if (c->tty_path)
5453 fprintf(f,
6ea832a2
LP
5454 "%sTTYPath: %s\n"
5455 "%sTTYReset: %s\n"
5456 "%sTTYVHangup: %s\n"
5457 "%sTTYVTDisallocate: %s\n",
5458 prefix, c->tty_path,
5459 prefix, yes_no(c->tty_reset),
5460 prefix, yes_no(c->tty_vhangup),
5461 prefix, yes_no(c->tty_vt_disallocate));
94f04347 5462
9f6444eb 5463 if (IN_SET(c->std_output,
9f6444eb
LP
5464 EXEC_OUTPUT_KMSG,
5465 EXEC_OUTPUT_JOURNAL,
9f6444eb
LP
5466 EXEC_OUTPUT_KMSG_AND_CONSOLE,
5467 EXEC_OUTPUT_JOURNAL_AND_CONSOLE) ||
5468 IN_SET(c->std_error,
9f6444eb
LP
5469 EXEC_OUTPUT_KMSG,
5470 EXEC_OUTPUT_JOURNAL,
9f6444eb
LP
5471 EXEC_OUTPUT_KMSG_AND_CONSOLE,
5472 EXEC_OUTPUT_JOURNAL_AND_CONSOLE)) {
f8b69d1d 5473
5ce70e5b 5474 _cleanup_free_ char *fac_str = NULL, *lvl_str = NULL;
f8b69d1d 5475
837df140
YW
5476 r = log_facility_unshifted_to_string_alloc(c->syslog_priority >> 3, &fac_str);
5477 if (r >= 0)
5478 fprintf(f, "%sSyslogFacility: %s\n", prefix, fac_str);
f8b69d1d 5479
837df140
YW
5480 r = log_level_to_string_alloc(LOG_PRI(c->syslog_priority), &lvl_str);
5481 if (r >= 0)
5482 fprintf(f, "%sSyslogLevel: %s\n", prefix, lvl_str);
f8b69d1d 5483 }
94f04347 5484
d3070fbd
LP
5485 if (c->log_level_max >= 0) {
5486 _cleanup_free_ char *t = NULL;
5487
5488 (void) log_level_to_string_alloc(c->log_level_max, &t);
5489
5490 fprintf(f, "%sLogLevelMax: %s\n", prefix, strna(t));
5491 }
5492
5ac1530e 5493 if (c->log_ratelimit_interval_usec > 0) {
90fc172e
AZ
5494 char buf_timespan[FORMAT_TIMESPAN_MAX];
5495
5496 fprintf(f,
5497 "%sLogRateLimitIntervalSec: %s\n",
5ac1530e 5498 prefix, format_timespan(buf_timespan, sizeof(buf_timespan), c->log_ratelimit_interval_usec, USEC_PER_SEC));
90fc172e
AZ
5499 }
5500
5ac1530e
ZJS
5501 if (c->log_ratelimit_burst > 0)
5502 fprintf(f, "%sLogRateLimitBurst: %u\n", prefix, c->log_ratelimit_burst);
90fc172e 5503
5b10116e
ZJS
5504 for (size_t j = 0; j < c->n_log_extra_fields; j++) {
5505 fprintf(f, "%sLogExtraFields: ", prefix);
5506 fwrite(c->log_extra_fields[j].iov_base,
5507 1, c->log_extra_fields[j].iov_len,
5508 f);
5509 fputc('\n', f);
d3070fbd
LP
5510 }
5511
91dd5f7c
LP
5512 if (c->log_namespace)
5513 fprintf(f, "%sLogNamespace: %s\n", prefix, c->log_namespace);
5514
07d46372
YW
5515 if (c->secure_bits) {
5516 _cleanup_free_ char *str = NULL;
5517
5518 r = secure_bits_to_string_alloc(c->secure_bits, &str);
5519 if (r >= 0)
5520 fprintf(f, "%sSecure Bits: %s\n", prefix, str);
5521 }
94f04347 5522
a103496c 5523 if (c->capability_bounding_set != CAP_ALL) {
dd1f5bd0 5524 _cleanup_free_ char *str = NULL;
94f04347 5525
dd1f5bd0
YW
5526 r = capability_set_to_string_alloc(c->capability_bounding_set, &str);
5527 if (r >= 0)
5528 fprintf(f, "%sCapabilityBoundingSet: %s\n", prefix, str);
755d4b67
IP
5529 }
5530
5531 if (c->capability_ambient_set != 0) {
dd1f5bd0 5532 _cleanup_free_ char *str = NULL;
755d4b67 5533
dd1f5bd0
YW
5534 r = capability_set_to_string_alloc(c->capability_ambient_set, &str);
5535 if (r >= 0)
5536 fprintf(f, "%sAmbientCapabilities: %s\n", prefix, str);
94f04347
LP
5537 }
5538
5539 if (c->user)
f2d3769a 5540 fprintf(f, "%sUser: %s\n", prefix, c->user);
94f04347 5541 if (c->group)
f2d3769a 5542 fprintf(f, "%sGroup: %s\n", prefix, c->group);
94f04347 5543
29206d46
LP
5544 fprintf(f, "%sDynamicUser: %s\n", prefix, yes_no(c->dynamic_user));
5545
ddc155b2 5546 strv_dump(f, prefix, "SupplementaryGroups", c->supplementary_groups);
94f04347 5547
5b6319dc 5548 if (c->pam_name)
f2d3769a 5549 fprintf(f, "%sPAMName: %s\n", prefix, c->pam_name);
5b6319dc 5550
ddc155b2
TM
5551 strv_dump(f, prefix, "ReadWritePaths", c->read_write_paths);
5552 strv_dump(f, prefix, "ReadOnlyPaths", c->read_only_paths);
5553 strv_dump(f, prefix, "InaccessiblePaths", c->inaccessible_paths);
5554 strv_dump(f, prefix, "ExecPaths", c->exec_paths);
5555 strv_dump(f, prefix, "NoExecPaths", c->no_exec_paths);
2e22afe9 5556
5b10116e
ZJS
5557 for (size_t i = 0; i < c->n_bind_mounts; i++)
5558 fprintf(f, "%s%s: %s%s:%s:%s\n", prefix,
5559 c->bind_mounts[i].read_only ? "BindReadOnlyPaths" : "BindPaths",
5560 c->bind_mounts[i].ignore_enoent ? "-": "",
5561 c->bind_mounts[i].source,
5562 c->bind_mounts[i].destination,
5563 c->bind_mounts[i].recursive ? "rbind" : "norbind");
d2d6c096 5564
5b10116e
ZJS
5565 for (size_t i = 0; i < c->n_temporary_filesystems; i++) {
5566 const TemporaryFileSystem *t = c->temporary_filesystems + i;
2abd4e38 5567
5b10116e
ZJS
5568 fprintf(f, "%sTemporaryFileSystem: %s%s%s\n", prefix,
5569 t->path,
5570 isempty(t->options) ? "" : ":",
5571 strempty(t->options));
5572 }
2abd4e38 5573
169c1bda
LP
5574 if (c->utmp_id)
5575 fprintf(f,
5576 "%sUtmpIdentifier: %s\n",
5577 prefix, c->utmp_id);
7b52a628
MS
5578
5579 if (c->selinux_context)
5580 fprintf(f,
5f8640fb
LP
5581 "%sSELinuxContext: %s%s\n",
5582 prefix, c->selinux_context_ignore ? "-" : "", c->selinux_context);
17df7223 5583
80c21aea
WC
5584 if (c->apparmor_profile)
5585 fprintf(f,
5586 "%sAppArmorProfile: %s%s\n",
5587 prefix, c->apparmor_profile_ignore ? "-" : "", c->apparmor_profile);
5588
5589 if (c->smack_process_label)
5590 fprintf(f,
5591 "%sSmackProcessLabel: %s%s\n",
5592 prefix, c->smack_process_label_ignore ? "-" : "", c->smack_process_label);
5593
050f7277 5594 if (c->personality != PERSONALITY_INVALID)
ac45f971
LP
5595 fprintf(f,
5596 "%sPersonality: %s\n",
5597 prefix, strna(personality_to_string(c->personality)));
5598
78e864e5
TM
5599 fprintf(f,
5600 "%sLockPersonality: %s\n",
5601 prefix, yes_no(c->lock_personality));
5602
17df7223 5603 if (c->syscall_filter) {
349cc4a5 5604#if HAVE_SECCOMP
8cfa775f 5605 void *id, *val;
17df7223 5606 bool first = true;
351a19b1 5607#endif
17df7223
LP
5608
5609 fprintf(f,
57183d11 5610 "%sSystemCallFilter: ",
17df7223
LP
5611 prefix);
5612
6b000af4 5613 if (!c->syscall_allow_list)
17df7223
LP
5614 fputc('~', f);
5615
349cc4a5 5616#if HAVE_SECCOMP
90e74a66 5617 HASHMAP_FOREACH_KEY(val, id, c->syscall_filter) {
17df7223 5618 _cleanup_free_ char *name = NULL;
8cfa775f
YW
5619 const char *errno_name = NULL;
5620 int num = PTR_TO_INT(val);
17df7223
LP
5621
5622 if (first)
5623 first = false;
5624 else
5625 fputc(' ', f);
5626
57183d11 5627 name = seccomp_syscall_resolve_num_arch(SCMP_ARCH_NATIVE, PTR_TO_INT(id) - 1);
17df7223 5628 fputs(strna(name), f);
8cfa775f
YW
5629
5630 if (num >= 0) {
005bfaf1 5631 errno_name = seccomp_errno_or_action_to_string(num);
8cfa775f
YW
5632 if (errno_name)
5633 fprintf(f, ":%s", errno_name);
5634 else
5635 fprintf(f, ":%d", num);
5636 }
17df7223 5637 }
351a19b1 5638#endif
17df7223
LP
5639
5640 fputc('\n', f);
5641 }
5642
57183d11 5643 if (c->syscall_archs) {
349cc4a5 5644#if HAVE_SECCOMP
57183d11
LP
5645 void *id;
5646#endif
5647
5648 fprintf(f,
5649 "%sSystemCallArchitectures:",
5650 prefix);
5651
349cc4a5 5652#if HAVE_SECCOMP
90e74a66 5653 SET_FOREACH(id, c->syscall_archs)
57183d11
LP
5654 fprintf(f, " %s", strna(seccomp_arch_to_string(PTR_TO_UINT32(id) - 1)));
5655#endif
5656 fputc('\n', f);
5657 }
5658
add00535
LP
5659 if (exec_context_restrict_namespaces_set(c)) {
5660 _cleanup_free_ char *s = NULL;
5661
86c2a9f1 5662 r = namespace_flags_to_string(c->restrict_namespaces, &s);
add00535
LP
5663 if (r >= 0)
5664 fprintf(f, "%sRestrictNamespaces: %s\n",
dd0395b5 5665 prefix, strna(s));
add00535
LP
5666 }
5667
a8d08f39
LP
5668 if (c->network_namespace_path)
5669 fprintf(f,
5670 "%sNetworkNamespacePath: %s\n",
5671 prefix, c->network_namespace_path);
5672
3df90f24 5673 if (c->syscall_errno > 0) {
005bfaf1 5674#if HAVE_SECCOMP
3df90f24 5675 const char *errno_name;
005bfaf1 5676#endif
3df90f24
YW
5677
5678 fprintf(f, "%sSystemCallErrorNumber: ", prefix);
5679
005bfaf1
TM
5680#if HAVE_SECCOMP
5681 errno_name = seccomp_errno_or_action_to_string(c->syscall_errno);
3df90f24 5682 if (errno_name)
005bfaf1 5683 fputs(errno_name, f);
3df90f24 5684 else
005bfaf1
TM
5685 fprintf(f, "%d", c->syscall_errno);
5686#endif
5687 fputc('\n', f);
3df90f24 5688 }
b3d13314 5689
5b10116e 5690 for (size_t i = 0; i < c->n_mount_images; i++) {
427353f6
LB
5691 MountOptions *o;
5692
79e20ceb 5693 fprintf(f, "%sMountImages: %s%s:%s", prefix,
b3d13314
LB
5694 c->mount_images[i].ignore_enoent ? "-": "",
5695 c->mount_images[i].source,
79e20ceb 5696 c->mount_images[i].destination);
427353f6 5697 LIST_FOREACH(mount_options, o, c->mount_images[i].mount_options)
79e20ceb 5698 fprintf(f, ":%s:%s",
427353f6 5699 partition_designator_to_string(o->partition_designator),
79e20ceb 5700 strempty(o->options));
427353f6
LB
5701 fprintf(f, "\n");
5702 }
93f59701
LB
5703
5704 for (size_t i = 0; i < c->n_extension_images; i++) {
5705 MountOptions *o;
5706
5707 fprintf(f, "%sExtensionImages: %s%s", prefix,
5708 c->extension_images[i].ignore_enoent ? "-": "",
5709 c->extension_images[i].source);
5710 LIST_FOREACH(mount_options, o, c->extension_images[i].mount_options)
5711 fprintf(f, ":%s:%s",
5712 partition_designator_to_string(o->partition_designator),
5713 strempty(o->options));
5714 fprintf(f, "\n");
5715 }
5cb5a6ff
LP
5716}
5717
34cf6c43 5718bool exec_context_maintains_privileges(const ExecContext *c) {
a931ad47
LP
5719 assert(c);
5720
61233823 5721 /* Returns true if the process forked off would run under
a931ad47
LP
5722 * an unchanged UID or as root. */
5723
5724 if (!c->user)
5725 return true;
5726
5727 if (streq(c->user, "root") || streq(c->user, "0"))
5728 return true;
5729
5730 return false;
5731}
5732
34cf6c43 5733int exec_context_get_effective_ioprio(const ExecContext *c) {
7f452159
LP
5734 int p;
5735
5736 assert(c);
5737
5738 if (c->ioprio_set)
5739 return c->ioprio;
5740
5741 p = ioprio_get(IOPRIO_WHO_PROCESS, 0);
5742 if (p < 0)
5743 return IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 4);
5744
5745 return p;
5746}
5747
5e98086d
ZJS
5748bool exec_context_get_effective_mount_apivfs(const ExecContext *c) {
5749 assert(c);
5750
61198784 5751 /* Explicit setting wins */
5e98086d
ZJS
5752 if (c->mount_apivfs_set)
5753 return c->mount_apivfs;
5754
61198784 5755 /* Default to "yes" if root directory or image are specified */
74e12520 5756 if (exec_context_with_rootfs(c))
61198784
ZJS
5757 return true;
5758
5e98086d
ZJS
5759 return false;
5760}
5761
d3070fbd 5762void exec_context_free_log_extra_fields(ExecContext *c) {
d3070fbd
LP
5763 assert(c);
5764
5b10116e 5765 for (size_t l = 0; l < c->n_log_extra_fields; l++)
d3070fbd
LP
5766 free(c->log_extra_fields[l].iov_base);
5767 c->log_extra_fields = mfree(c->log_extra_fields);
5768 c->n_log_extra_fields = 0;
5769}
5770
6f765baf
LP
5771void exec_context_revert_tty(ExecContext *c) {
5772 int r;
5773
5774 assert(c);
5775
5776 /* First, reset the TTY (possibly kicking everybody else from the TTY) */
5777 exec_context_tty_reset(c, NULL);
5778
5779 /* And then undo what chown_terminal() did earlier. Note that we only do this if we have a path
5780 * configured. If the TTY was passed to us as file descriptor we assume the TTY is opened and managed
5781 * by whoever passed it to us and thus knows better when and how to chmod()/chown() it back. */
5782
5783 if (exec_context_may_touch_tty(c)) {
5784 const char *path;
5785
5786 path = exec_context_tty_path(c);
5787 if (path) {
5788 r = chmod_and_chown(path, TTY_MODE, 0, TTY_GID);
5789 if (r < 0 && r != -ENOENT)
5790 log_warning_errno(r, "Failed to reset TTY ownership/access mode of %s, ignoring: %m", path);
5791 }
5792 }
5793}
5794
4c2f5842
LP
5795int exec_context_get_clean_directories(
5796 ExecContext *c,
5797 char **prefix,
5798 ExecCleanMask mask,
5799 char ***ret) {
5800
5801 _cleanup_strv_free_ char **l = NULL;
4c2f5842
LP
5802 int r;
5803
5804 assert(c);
5805 assert(prefix);
5806 assert(ret);
5807
5b10116e 5808 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
4c2f5842
LP
5809 char **i;
5810
5811 if (!FLAGS_SET(mask, 1U << t))
5812 continue;
5813
5814 if (!prefix[t])
5815 continue;
5816
5817 STRV_FOREACH(i, c->directories[t].paths) {
5818 char *j;
5819
5820 j = path_join(prefix[t], *i);
5821 if (!j)
5822 return -ENOMEM;
5823
5824 r = strv_consume(&l, j);
5825 if (r < 0)
5826 return r;
7f622a19
YW
5827
5828 /* Also remove private directories unconditionally. */
5829 if (t != EXEC_DIRECTORY_CONFIGURATION) {
5830 j = path_join(prefix[t], "private", *i);
5831 if (!j)
5832 return -ENOMEM;
5833
5834 r = strv_consume(&l, j);
5835 if (r < 0)
5836 return r;
5837 }
4c2f5842
LP
5838 }
5839 }
5840
5841 *ret = TAKE_PTR(l);
5842 return 0;
5843}
5844
5845int exec_context_get_clean_mask(ExecContext *c, ExecCleanMask *ret) {
5846 ExecCleanMask mask = 0;
5847
5848 assert(c);
5849 assert(ret);
5850
5851 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++)
5852 if (!strv_isempty(c->directories[t].paths))
5853 mask |= 1U << t;
5854
5855 *ret = mask;
5856 return 0;
5857}
5858
b58b4116 5859void exec_status_start(ExecStatus *s, pid_t pid) {
034c6ed7 5860 assert(s);
5cb5a6ff 5861
2ed26ed0
LP
5862 *s = (ExecStatus) {
5863 .pid = pid,
5864 };
5865
b58b4116
LP
5866 dual_timestamp_get(&s->start_timestamp);
5867}
5868
34cf6c43 5869void exec_status_exit(ExecStatus *s, const ExecContext *context, pid_t pid, int code, int status) {
b58b4116
LP
5870 assert(s);
5871
d46b79bb 5872 if (s->pid != pid)
2ed26ed0
LP
5873 *s = (ExecStatus) {
5874 .pid = pid,
5875 };
b58b4116 5876
63983207 5877 dual_timestamp_get(&s->exit_timestamp);
9fb86720 5878
034c6ed7
LP
5879 s->code = code;
5880 s->status = status;
169c1bda 5881
6f765baf
LP
5882 if (context && context->utmp_id)
5883 (void) utmp_put_dead_process(context->utmp_id, pid, code, status);
9fb86720
LP
5884}
5885
6a1d4d9f
LP
5886void exec_status_reset(ExecStatus *s) {
5887 assert(s);
5888
5889 *s = (ExecStatus) {};
5890}
5891
34cf6c43 5892void exec_status_dump(const ExecStatus *s, FILE *f, const char *prefix) {
9fb86720
LP
5893 char buf[FORMAT_TIMESTAMP_MAX];
5894
5895 assert(s);
5896 assert(f);
5897
9fb86720
LP
5898 if (s->pid <= 0)
5899 return;
5900
4c940960
LP
5901 prefix = strempty(prefix);
5902
9fb86720 5903 fprintf(f,
ccd06097
ZJS
5904 "%sPID: "PID_FMT"\n",
5905 prefix, s->pid);
9fb86720 5906
af9d16e1 5907 if (dual_timestamp_is_set(&s->start_timestamp))
9fb86720
LP
5908 fprintf(f,
5909 "%sStart Timestamp: %s\n",
63983207 5910 prefix, format_timestamp(buf, sizeof(buf), s->start_timestamp.realtime));
9fb86720 5911
af9d16e1 5912 if (dual_timestamp_is_set(&s->exit_timestamp))
9fb86720
LP
5913 fprintf(f,
5914 "%sExit Timestamp: %s\n"
5915 "%sExit Code: %s\n"
5916 "%sExit Status: %i\n",
63983207 5917 prefix, format_timestamp(buf, sizeof(buf), s->exit_timestamp.realtime),
9fb86720
LP
5918 prefix, sigchld_code_to_string(s->code),
5919 prefix, s->status);
5cb5a6ff 5920}
44d8db9e 5921
34cf6c43 5922static char *exec_command_line(char **argv) {
44d8db9e
LP
5923 size_t k;
5924 char *n, *p, **a;
5925 bool first = true;
5926
9e2f7c11 5927 assert(argv);
44d8db9e 5928
9164977d 5929 k = 1;
9e2f7c11 5930 STRV_FOREACH(a, argv)
44d8db9e
LP
5931 k += strlen(*a)+3;
5932
5cd9cd35
LP
5933 n = new(char, k);
5934 if (!n)
44d8db9e
LP
5935 return NULL;
5936
5937 p = n;
9e2f7c11 5938 STRV_FOREACH(a, argv) {
44d8db9e
LP
5939
5940 if (!first)
5941 *(p++) = ' ';
5942 else
5943 first = false;
5944
5945 if (strpbrk(*a, WHITESPACE)) {
5946 *(p++) = '\'';
5947 p = stpcpy(p, *a);
5948 *(p++) = '\'';
5949 } else
5950 p = stpcpy(p, *a);
5951
5952 }
5953
9164977d
LP
5954 *p = 0;
5955
44d8db9e
LP
5956 /* FIXME: this doesn't really handle arguments that have
5957 * spaces and ticks in them */
5958
5959 return n;
5960}
5961
34cf6c43 5962static void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
e1d75803 5963 _cleanup_free_ char *cmd = NULL;
4c940960 5964 const char *prefix2;
44d8db9e
LP
5965
5966 assert(c);
5967 assert(f);
5968
4c940960 5969 prefix = strempty(prefix);
63c372cb 5970 prefix2 = strjoina(prefix, "\t");
44d8db9e 5971
9e2f7c11 5972 cmd = exec_command_line(c->argv);
44d8db9e
LP
5973 fprintf(f,
5974 "%sCommand Line: %s\n",
4bbccb02 5975 prefix, cmd ? cmd : strerror_safe(ENOMEM));
44d8db9e 5976
9fb86720 5977 exec_status_dump(&c->exec_status, f, prefix2);
44d8db9e
LP
5978}
5979
5980void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
5981 assert(f);
5982
4c940960 5983 prefix = strempty(prefix);
44d8db9e
LP
5984
5985 LIST_FOREACH(command, c, c)
5986 exec_command_dump(c, f, prefix);
5987}
94f04347 5988
a6a80b4f
LP
5989void exec_command_append_list(ExecCommand **l, ExecCommand *e) {
5990 ExecCommand *end;
5991
5992 assert(l);
5993 assert(e);
5994
5995 if (*l) {
35b8ca3a 5996 /* It's kind of important, that we keep the order here */
71fda00f
LP
5997 LIST_FIND_TAIL(command, *l, end);
5998 LIST_INSERT_AFTER(command, *l, end, e);
a6a80b4f
LP
5999 } else
6000 *l = e;
6001}
6002
26fd040d
LP
6003int exec_command_set(ExecCommand *c, const char *path, ...) {
6004 va_list ap;
6005 char **l, *p;
6006
6007 assert(c);
6008 assert(path);
6009
6010 va_start(ap, path);
6011 l = strv_new_ap(path, ap);
6012 va_end(ap);
6013
6014 if (!l)
6015 return -ENOMEM;
6016
250a918d
LP
6017 p = strdup(path);
6018 if (!p) {
26fd040d
LP
6019 strv_free(l);
6020 return -ENOMEM;
6021 }
6022
6897dfe8 6023 free_and_replace(c->path, p);
26fd040d 6024
130d3d22 6025 return strv_free_and_replace(c->argv, l);
26fd040d
LP
6026}
6027
86b23b07 6028int exec_command_append(ExecCommand *c, const char *path, ...) {
e63ff941 6029 _cleanup_strv_free_ char **l = NULL;
86b23b07 6030 va_list ap;
86b23b07
JS
6031 int r;
6032
6033 assert(c);
6034 assert(path);
6035
6036 va_start(ap, path);
6037 l = strv_new_ap(path, ap);
6038 va_end(ap);
6039
6040 if (!l)
6041 return -ENOMEM;
6042
e287086b 6043 r = strv_extend_strv(&c->argv, l, false);
e63ff941 6044 if (r < 0)
86b23b07 6045 return r;
86b23b07
JS
6046
6047 return 0;
6048}
6049
e8a565cb
YW
6050static void *remove_tmpdir_thread(void *p) {
6051 _cleanup_free_ char *path = p;
86b23b07 6052
e8a565cb
YW
6053 (void) rm_rf(path, REMOVE_ROOT|REMOVE_PHYSICAL);
6054 return NULL;
6055}
6056
6057static ExecRuntime* exec_runtime_free(ExecRuntime *rt, bool destroy) {
6058 int r;
6059
6060 if (!rt)
6061 return NULL;
6062
6063 if (rt->manager)
6064 (void) hashmap_remove(rt->manager->exec_runtime_by_id, rt->id);
6065
6066 /* When destroy is true, then rm_rf tmp_dir and var_tmp_dir. */
56a13a49
ZJS
6067
6068 if (destroy && rt->tmp_dir && !streq(rt->tmp_dir, RUN_SYSTEMD_EMPTY)) {
e8a565cb
YW
6069 log_debug("Spawning thread to nuke %s", rt->tmp_dir);
6070
6071 r = asynchronous_job(remove_tmpdir_thread, rt->tmp_dir);
56a13a49 6072 if (r < 0)
e8a565cb 6073 log_warning_errno(r, "Failed to nuke %s: %m", rt->tmp_dir);
56a13a49
ZJS
6074 else
6075 rt->tmp_dir = NULL;
e8a565cb 6076 }
613b411c 6077
56a13a49 6078 if (destroy && rt->var_tmp_dir && !streq(rt->var_tmp_dir, RUN_SYSTEMD_EMPTY)) {
e8a565cb
YW
6079 log_debug("Spawning thread to nuke %s", rt->var_tmp_dir);
6080
6081 r = asynchronous_job(remove_tmpdir_thread, rt->var_tmp_dir);
56a13a49 6082 if (r < 0)
e8a565cb 6083 log_warning_errno(r, "Failed to nuke %s: %m", rt->var_tmp_dir);
56a13a49
ZJS
6084 else
6085 rt->var_tmp_dir = NULL;
e8a565cb
YW
6086 }
6087
6088 rt->id = mfree(rt->id);
6089 rt->tmp_dir = mfree(rt->tmp_dir);
6090 rt->var_tmp_dir = mfree(rt->var_tmp_dir);
6091 safe_close_pair(rt->netns_storage_socket);
a70581ff 6092 safe_close_pair(rt->ipcns_storage_socket);
e8a565cb
YW
6093 return mfree(rt);
6094}
6095
6096static void exec_runtime_freep(ExecRuntime **rt) {
da6bc6ed 6097 (void) exec_runtime_free(*rt, false);
e8a565cb
YW
6098}
6099
56a13a49
ZJS
6100static int exec_runtime_allocate(ExecRuntime **ret, const char *id) {
6101 _cleanup_free_ char *id_copy = NULL;
8e8009dc 6102 ExecRuntime *n;
613b411c 6103
8e8009dc 6104 assert(ret);
613b411c 6105
56a13a49
ZJS
6106 id_copy = strdup(id);
6107 if (!id_copy)
6108 return -ENOMEM;
6109
8e8009dc
LP
6110 n = new(ExecRuntime, 1);
6111 if (!n)
613b411c
LP
6112 return -ENOMEM;
6113
8e8009dc 6114 *n = (ExecRuntime) {
56a13a49 6115 .id = TAKE_PTR(id_copy),
8e8009dc 6116 .netns_storage_socket = { -1, -1 },
a70581ff 6117 .ipcns_storage_socket = { -1, -1 },
8e8009dc
LP
6118 };
6119
6120 *ret = n;
613b411c
LP
6121 return 0;
6122}
6123
e8a565cb
YW
6124static int exec_runtime_add(
6125 Manager *m,
6126 const char *id,
56a13a49
ZJS
6127 char **tmp_dir,
6128 char **var_tmp_dir,
6129 int netns_storage_socket[2],
a70581ff 6130 int ipcns_storage_socket[2],
e8a565cb
YW
6131 ExecRuntime **ret) {
6132
6133 _cleanup_(exec_runtime_freep) ExecRuntime *rt = NULL;
613b411c
LP
6134 int r;
6135
e8a565cb 6136 assert(m);
613b411c
LP
6137 assert(id);
6138
a70581ff 6139 /* tmp_dir, var_tmp_dir, {net,ipc}ns_storage_socket fds are donated on success */
56a13a49 6140
56a13a49 6141 r = exec_runtime_allocate(&rt, id);
613b411c
LP
6142 if (r < 0)
6143 return r;
6144
63083706 6145 r = hashmap_ensure_put(&m->exec_runtime_by_id, &string_hash_ops, rt->id, rt);
56a13a49
ZJS
6146 if (r < 0)
6147 return r;
e8a565cb 6148
56a13a49
ZJS
6149 assert(!!rt->tmp_dir == !!rt->var_tmp_dir); /* We require both to be set together */
6150 rt->tmp_dir = TAKE_PTR(*tmp_dir);
6151 rt->var_tmp_dir = TAKE_PTR(*var_tmp_dir);
e8a565cb
YW
6152
6153 if (netns_storage_socket) {
56a13a49
ZJS
6154 rt->netns_storage_socket[0] = TAKE_FD(netns_storage_socket[0]);
6155 rt->netns_storage_socket[1] = TAKE_FD(netns_storage_socket[1]);
613b411c
LP
6156 }
6157
a70581ff
XR
6158 if (ipcns_storage_socket) {
6159 rt->ipcns_storage_socket[0] = TAKE_FD(ipcns_storage_socket[0]);
6160 rt->ipcns_storage_socket[1] = TAKE_FD(ipcns_storage_socket[1]);
6161 }
6162
e8a565cb
YW
6163 rt->manager = m;
6164
6165 if (ret)
6166 *ret = rt;
e8a565cb 6167 /* do not remove created ExecRuntime object when the operation succeeds. */
56a13a49 6168 TAKE_PTR(rt);
e8a565cb
YW
6169 return 0;
6170}
6171
74aaf59b
LP
6172static int exec_runtime_make(
6173 Manager *m,
6174 const ExecContext *c,
6175 const char *id,
6176 ExecRuntime **ret) {
6177
56a13a49 6178 _cleanup_(namespace_cleanup_tmpdirp) char *tmp_dir = NULL, *var_tmp_dir = NULL;
a70581ff 6179 _cleanup_close_pair_ int netns_storage_socket[2] = { -1, -1 }, ipcns_storage_socket[2] = { -1, -1 };
e8a565cb
YW
6180 int r;
6181
6182 assert(m);
6183 assert(c);
6184 assert(id);
6185
6186 /* It is not necessary to create ExecRuntime object. */
a70581ff 6187 if (!c->private_network && !c->private_ipc && !c->private_tmp && !c->network_namespace_path) {
74aaf59b 6188 *ret = NULL;
e8a565cb 6189 return 0;
74aaf59b 6190 }
e8a565cb 6191
efa2f3a1
TM
6192 if (c->private_tmp &&
6193 !(prefixed_path_strv_contains(c->inaccessible_paths, "/tmp") &&
6194 (prefixed_path_strv_contains(c->inaccessible_paths, "/var/tmp") ||
6195 prefixed_path_strv_contains(c->inaccessible_paths, "/var")))) {
e8a565cb 6196 r = setup_tmp_dirs(id, &tmp_dir, &var_tmp_dir);
613b411c
LP
6197 if (r < 0)
6198 return r;
6199 }
6200
a8d08f39 6201 if (c->private_network || c->network_namespace_path) {
e8a565cb
YW
6202 if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, netns_storage_socket) < 0)
6203 return -errno;
6204 }
6205
a70581ff
XR
6206 if (c->private_ipc || c->ipc_namespace_path) {
6207 if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, ipcns_storage_socket) < 0)
6208 return -errno;
6209 }
6210
6211 r = exec_runtime_add(m, id, &tmp_dir, &var_tmp_dir, netns_storage_socket, ipcns_storage_socket, ret);
e8a565cb
YW
6212 if (r < 0)
6213 return r;
6214
613b411c
LP
6215 return 1;
6216}
6217
e8a565cb
YW
6218int exec_runtime_acquire(Manager *m, const ExecContext *c, const char *id, bool create, ExecRuntime **ret) {
6219 ExecRuntime *rt;
6220 int r;
613b411c 6221
e8a565cb
YW
6222 assert(m);
6223 assert(id);
6224 assert(ret);
6225
6226 rt = hashmap_get(m->exec_runtime_by_id, id);
6227 if (rt)
6228 /* We already have a ExecRuntime object, let's increase the ref count and reuse it */
6229 goto ref;
6230
74aaf59b
LP
6231 if (!create) {
6232 *ret = NULL;
e8a565cb 6233 return 0;
74aaf59b 6234 }
e8a565cb
YW
6235
6236 /* If not found, then create a new object. */
6237 r = exec_runtime_make(m, c, id, &rt);
74aaf59b 6238 if (r < 0)
e8a565cb 6239 return r;
74aaf59b
LP
6240 if (r == 0) {
6241 /* When r == 0, it is not necessary to create ExecRuntime object. */
6242 *ret = NULL;
6243 return 0;
6244 }
613b411c 6245
e8a565cb
YW
6246ref:
6247 /* increment reference counter. */
6248 rt->n_ref++;
6249 *ret = rt;
6250 return 1;
6251}
613b411c 6252
e8a565cb
YW
6253ExecRuntime *exec_runtime_unref(ExecRuntime *rt, bool destroy) {
6254 if (!rt)
613b411c
LP
6255 return NULL;
6256
e8a565cb 6257 assert(rt->n_ref > 0);
613b411c 6258
e8a565cb
YW
6259 rt->n_ref--;
6260 if (rt->n_ref > 0)
f2341e0a
LP
6261 return NULL;
6262
e8a565cb 6263 return exec_runtime_free(rt, destroy);
613b411c
LP
6264}
6265
e8a565cb
YW
6266int exec_runtime_serialize(const Manager *m, FILE *f, FDSet *fds) {
6267 ExecRuntime *rt;
e8a565cb
YW
6268
6269 assert(m);
613b411c
LP
6270 assert(f);
6271 assert(fds);
6272
90e74a66 6273 HASHMAP_FOREACH(rt, m->exec_runtime_by_id) {
e8a565cb 6274 fprintf(f, "exec-runtime=%s", rt->id);
613b411c 6275
e8a565cb
YW
6276 if (rt->tmp_dir)
6277 fprintf(f, " tmp-dir=%s", rt->tmp_dir);
613b411c 6278
e8a565cb
YW
6279 if (rt->var_tmp_dir)
6280 fprintf(f, " var-tmp-dir=%s", rt->var_tmp_dir);
613b411c 6281
e8a565cb
YW
6282 if (rt->netns_storage_socket[0] >= 0) {
6283 int copy;
613b411c 6284
e8a565cb
YW
6285 copy = fdset_put_dup(fds, rt->netns_storage_socket[0]);
6286 if (copy < 0)
6287 return copy;
613b411c 6288
e8a565cb
YW
6289 fprintf(f, " netns-socket-0=%i", copy);
6290 }
613b411c 6291
e8a565cb
YW
6292 if (rt->netns_storage_socket[1] >= 0) {
6293 int copy;
613b411c 6294
e8a565cb
YW
6295 copy = fdset_put_dup(fds, rt->netns_storage_socket[1]);
6296 if (copy < 0)
6297 return copy;
613b411c 6298
e8a565cb
YW
6299 fprintf(f, " netns-socket-1=%i", copy);
6300 }
6301
a70581ff
XR
6302 if (rt->ipcns_storage_socket[0] >= 0) {
6303 int copy;
6304
6305 copy = fdset_put_dup(fds, rt->ipcns_storage_socket[0]);
6306 if (copy < 0)
6307 return copy;
6308
6309 fprintf(f, " ipcns-socket-0=%i", copy);
6310 }
6311
6312 if (rt->ipcns_storage_socket[1] >= 0) {
6313 int copy;
6314
6315 copy = fdset_put_dup(fds, rt->ipcns_storage_socket[1]);
6316 if (copy < 0)
6317 return copy;
6318
6319 fprintf(f, " ipcns-socket-1=%i", copy);
6320 }
6321
e8a565cb 6322 fputc('\n', f);
613b411c
LP
6323 }
6324
6325 return 0;
6326}
6327
e8a565cb
YW
6328int exec_runtime_deserialize_compat(Unit *u, const char *key, const char *value, FDSet *fds) {
6329 _cleanup_(exec_runtime_freep) ExecRuntime *rt_create = NULL;
6330 ExecRuntime *rt;
613b411c
LP
6331 int r;
6332
e8a565cb
YW
6333 /* This is for the migration from old (v237 or earlier) deserialization text.
6334 * Due to the bug #7790, this may not work with the units that use JoinsNamespaceOf=.
6335 * Even if the ExecRuntime object originally created by the other unit, we cannot judge
6336 * so or not from the serialized text, then we always creates a new object owned by this. */
6337
6338 assert(u);
613b411c
LP
6339 assert(key);
6340 assert(value);
6341
e8a565cb
YW
6342 /* Manager manages ExecRuntime objects by the unit id.
6343 * So, we omit the serialized text when the unit does not have id (yet?)... */
6344 if (isempty(u->id)) {
6345 log_unit_debug(u, "Invocation ID not found. Dropping runtime parameter.");
6346 return 0;
6347 }
613b411c 6348
e8a565cb
YW
6349 r = hashmap_ensure_allocated(&u->manager->exec_runtime_by_id, &string_hash_ops);
6350 if (r < 0) {
6351 log_unit_debug_errno(u, r, "Failed to allocate storage for runtime parameter: %m");
6352 return 0;
6353 }
6354
6355 rt = hashmap_get(u->manager->exec_runtime_by_id, u->id);
6356 if (!rt) {
56a13a49 6357 r = exec_runtime_allocate(&rt_create, u->id);
613b411c 6358 if (r < 0)
f2341e0a 6359 return log_oom();
613b411c 6360
e8a565cb
YW
6361 rt = rt_create;
6362 }
6363
6364 if (streq(key, "tmp-dir")) {
6365 char *copy;
6366
613b411c
LP
6367 copy = strdup(value);
6368 if (!copy)
6369 return log_oom();
6370
e8a565cb 6371 free_and_replace(rt->tmp_dir, copy);
613b411c
LP
6372
6373 } else if (streq(key, "var-tmp-dir")) {
6374 char *copy;
6375
613b411c
LP
6376 copy = strdup(value);
6377 if (!copy)
6378 return log_oom();
6379
e8a565cb 6380 free_and_replace(rt->var_tmp_dir, copy);
613b411c
LP
6381
6382 } else if (streq(key, "netns-socket-0")) {
6383 int fd;
6384
e8a565cb 6385 if (safe_atoi(value, &fd) < 0 || !fdset_contains(fds, fd)) {
f2341e0a 6386 log_unit_debug(u, "Failed to parse netns socket value: %s", value);
e8a565cb 6387 return 0;
613b411c 6388 }
e8a565cb
YW
6389
6390 safe_close(rt->netns_storage_socket[0]);
6391 rt->netns_storage_socket[0] = fdset_remove(fds, fd);
6392
613b411c
LP
6393 } else if (streq(key, "netns-socket-1")) {
6394 int fd;
6395
e8a565cb 6396 if (safe_atoi(value, &fd) < 0 || !fdset_contains(fds, fd)) {
f2341e0a 6397 log_unit_debug(u, "Failed to parse netns socket value: %s", value);
e8a565cb 6398 return 0;
613b411c 6399 }
e8a565cb
YW
6400
6401 safe_close(rt->netns_storage_socket[1]);
6402 rt->netns_storage_socket[1] = fdset_remove(fds, fd);
a70581ff
XR
6403
6404 } else if (streq(key, "ipcns-socket-0")) {
6405 int fd;
6406
6407 if (safe_atoi(value, &fd) < 0 || !fdset_contains(fds, fd)) {
6408 log_unit_debug(u, "Failed to parse ipcns socket value: %s", value);
6409 return 0;
6410 }
6411
6412 safe_close(rt->ipcns_storage_socket[0]);
6413 rt->ipcns_storage_socket[0] = fdset_remove(fds, fd);
6414
6415 } else if (streq(key, "ipcns-socket-1")) {
6416 int fd;
6417
6418 if (safe_atoi(value, &fd) < 0 || !fdset_contains(fds, fd)) {
6419 log_unit_debug(u, "Failed to parse ipcns socket value: %s", value);
6420 return 0;
6421 }
6422
6423 safe_close(rt->ipcns_storage_socket[1]);
6424 rt->ipcns_storage_socket[1] = fdset_remove(fds, fd);
613b411c
LP
6425 } else
6426 return 0;
6427
e8a565cb
YW
6428 /* If the object is newly created, then put it to the hashmap which manages ExecRuntime objects. */
6429 if (rt_create) {
6430 r = hashmap_put(u->manager->exec_runtime_by_id, rt_create->id, rt_create);
6431 if (r < 0) {
3fe91079 6432 log_unit_debug_errno(u, r, "Failed to put runtime parameter to manager's storage: %m");
e8a565cb
YW
6433 return 0;
6434 }
613b411c 6435
e8a565cb 6436 rt_create->manager = u->manager;
613b411c 6437
e8a565cb 6438 /* Avoid cleanup */
56a13a49 6439 TAKE_PTR(rt_create);
e8a565cb 6440 }
98b47d54 6441
e8a565cb
YW
6442 return 1;
6443}
613b411c 6444
56a13a49
ZJS
6445int exec_runtime_deserialize_one(Manager *m, const char *value, FDSet *fds) {
6446 _cleanup_free_ char *tmp_dir = NULL, *var_tmp_dir = NULL;
6447 char *id = NULL;
a70581ff 6448 int r, netns_fdpair[] = {-1, -1}, ipcns_fdpair[] = {-1, -1};
e8a565cb
YW
6449 const char *p, *v = value;
6450 size_t n;
613b411c 6451
e8a565cb
YW
6452 assert(m);
6453 assert(value);
6454 assert(fds);
98b47d54 6455
e8a565cb
YW
6456 n = strcspn(v, " ");
6457 id = strndupa(v, n);
6458 if (v[n] != ' ')
6459 goto finalize;
6460 p = v + n + 1;
6461
6462 v = startswith(p, "tmp-dir=");
6463 if (v) {
6464 n = strcspn(v, " ");
56a13a49
ZJS
6465 tmp_dir = strndup(v, n);
6466 if (!tmp_dir)
6467 return log_oom();
e8a565cb
YW
6468 if (v[n] != ' ')
6469 goto finalize;
6470 p = v + n + 1;
6471 }
6472
6473 v = startswith(p, "var-tmp-dir=");
6474 if (v) {
6475 n = strcspn(v, " ");
56a13a49
ZJS
6476 var_tmp_dir = strndup(v, n);
6477 if (!var_tmp_dir)
6478 return log_oom();
e8a565cb
YW
6479 if (v[n] != ' ')
6480 goto finalize;
6481 p = v + n + 1;
6482 }
6483
6484 v = startswith(p, "netns-socket-0=");
6485 if (v) {
6486 char *buf;
6487
6488 n = strcspn(v, " ");
6489 buf = strndupa(v, n);
c413bb28 6490
a70581ff 6491 r = safe_atoi(buf, &netns_fdpair[0]);
c413bb28
ZJS
6492 if (r < 0)
6493 return log_debug_errno(r, "Unable to parse exec-runtime specification netns-socket-0=%s: %m", buf);
a70581ff 6494 if (!fdset_contains(fds, netns_fdpair[0]))
c413bb28 6495 return log_debug_errno(SYNTHETIC_ERRNO(EBADF),
a70581ff
XR
6496 "exec-runtime specification netns-socket-0= refers to unknown fd %d: %m", netns_fdpair[0]);
6497 netns_fdpair[0] = fdset_remove(fds, netns_fdpair[0]);
e8a565cb
YW
6498 if (v[n] != ' ')
6499 goto finalize;
6500 p = v + n + 1;
613b411c
LP
6501 }
6502
e8a565cb
YW
6503 v = startswith(p, "netns-socket-1=");
6504 if (v) {
6505 char *buf;
98b47d54 6506
e8a565cb
YW
6507 n = strcspn(v, " ");
6508 buf = strndupa(v, n);
a70581ff
XR
6509
6510 r = safe_atoi(buf, &netns_fdpair[1]);
c413bb28
ZJS
6511 if (r < 0)
6512 return log_debug_errno(r, "Unable to parse exec-runtime specification netns-socket-1=%s: %m", buf);
a70581ff
XR
6513 if (!fdset_contains(fds, netns_fdpair[1]))
6514 return log_debug_errno(SYNTHETIC_ERRNO(EBADF),
6515 "exec-runtime specification netns-socket-1= refers to unknown fd %d: %m", netns_fdpair[1]);
6516 netns_fdpair[1] = fdset_remove(fds, netns_fdpair[1]);
6517 if (v[n] != ' ')
6518 goto finalize;
6519 p = v + n + 1;
6520 }
6521
6522 v = startswith(p, "ipcns-socket-0=");
6523 if (v) {
6524 char *buf;
6525
6526 n = strcspn(v, " ");
6527 buf = strndupa(v, n);
6528
6529 r = safe_atoi(buf, &ipcns_fdpair[0]);
6530 if (r < 0)
6531 return log_debug_errno(r, "Unable to parse exec-runtime specification ipcns-socket-0=%s: %m", buf);
6532 if (!fdset_contains(fds, ipcns_fdpair[0]))
6533 return log_debug_errno(SYNTHETIC_ERRNO(EBADF),
6534 "exec-runtime specification ipcns-socket-0= refers to unknown fd %d: %m", ipcns_fdpair[0]);
6535 ipcns_fdpair[0] = fdset_remove(fds, ipcns_fdpair[0]);
6536 if (v[n] != ' ')
6537 goto finalize;
6538 p = v + n + 1;
6539 }
6540
6541 v = startswith(p, "ipcns-socket-1=");
6542 if (v) {
6543 char *buf;
6544
6545 n = strcspn(v, " ");
6546 buf = strndupa(v, n);
6547
6548 r = safe_atoi(buf, &ipcns_fdpair[1]);
6549 if (r < 0)
6550 return log_debug_errno(r, "Unable to parse exec-runtime specification ipcns-socket-1=%s: %m", buf);
6551 if (!fdset_contains(fds, ipcns_fdpair[1]))
c413bb28 6552 return log_debug_errno(SYNTHETIC_ERRNO(EBADF),
a70581ff
XR
6553 "exec-runtime specification ipcns-socket-1= refers to unknown fd %d: %m", ipcns_fdpair[1]);
6554 ipcns_fdpair[1] = fdset_remove(fds, ipcns_fdpair[1]);
e8a565cb 6555 }
98b47d54 6556
e8a565cb 6557finalize:
a70581ff 6558 r = exec_runtime_add(m, id, &tmp_dir, &var_tmp_dir, netns_fdpair, ipcns_fdpair, NULL);
7d853ca6 6559 if (r < 0)
56a13a49
ZJS
6560 return log_debug_errno(r, "Failed to add exec-runtime: %m");
6561 return 0;
e8a565cb 6562}
613b411c 6563
e8a565cb
YW
6564void exec_runtime_vacuum(Manager *m) {
6565 ExecRuntime *rt;
e8a565cb
YW
6566
6567 assert(m);
6568
6569 /* Free unreferenced ExecRuntime objects. This is used after manager deserialization process. */
6570
90e74a66 6571 HASHMAP_FOREACH(rt, m->exec_runtime_by_id) {
e8a565cb
YW
6572 if (rt->n_ref > 0)
6573 continue;
6574
6575 (void) exec_runtime_free(rt, false);
6576 }
613b411c
LP
6577}
6578
b9c04eaf
YW
6579void exec_params_clear(ExecParameters *p) {
6580 if (!p)
6581 return;
6582
c3f8a065
LP
6583 p->environment = strv_free(p->environment);
6584 p->fd_names = strv_free(p->fd_names);
6585 p->fds = mfree(p->fds);
6586 p->exec_fd = safe_close(p->exec_fd);
b9c04eaf
YW
6587}
6588
bb0c0d6f
LP
6589ExecSetCredential *exec_set_credential_free(ExecSetCredential *sc) {
6590 if (!sc)
6591 return NULL;
6592
6593 free(sc->id);
6594 free(sc->data);
6595 return mfree(sc);
6596}
6597
6598DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(exec_set_credential_hash_ops, char, string_hash_func, string_compare_func, ExecSetCredential, exec_set_credential_free);
6599
80876c20
LP
6600static const char* const exec_input_table[_EXEC_INPUT_MAX] = {
6601 [EXEC_INPUT_NULL] = "null",
6602 [EXEC_INPUT_TTY] = "tty",
6603 [EXEC_INPUT_TTY_FORCE] = "tty-force",
4f2d528d 6604 [EXEC_INPUT_TTY_FAIL] = "tty-fail",
52c239d7
LB
6605 [EXEC_INPUT_SOCKET] = "socket",
6606 [EXEC_INPUT_NAMED_FD] = "fd",
08f3be7a 6607 [EXEC_INPUT_DATA] = "data",
2038c3f5 6608 [EXEC_INPUT_FILE] = "file",
80876c20
LP
6609};
6610
8a0867d6
LP
6611DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput);
6612
94f04347 6613static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = {
80876c20 6614 [EXEC_OUTPUT_INHERIT] = "inherit",
94f04347 6615 [EXEC_OUTPUT_NULL] = "null",
80876c20 6616 [EXEC_OUTPUT_TTY] = "tty",
9a6bca7a 6617 [EXEC_OUTPUT_KMSG] = "kmsg",
28dbc1e8 6618 [EXEC_OUTPUT_KMSG_AND_CONSOLE] = "kmsg+console",
706343f4
LP
6619 [EXEC_OUTPUT_JOURNAL] = "journal",
6620 [EXEC_OUTPUT_JOURNAL_AND_CONSOLE] = "journal+console",
52c239d7
LB
6621 [EXEC_OUTPUT_SOCKET] = "socket",
6622 [EXEC_OUTPUT_NAMED_FD] = "fd",
2038c3f5 6623 [EXEC_OUTPUT_FILE] = "file",
566b7d23 6624 [EXEC_OUTPUT_FILE_APPEND] = "append",
8d7dab1f 6625 [EXEC_OUTPUT_FILE_TRUNCATE] = "truncate",
94f04347
LP
6626};
6627
6628DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput);
023a4f67
LP
6629
6630static const char* const exec_utmp_mode_table[_EXEC_UTMP_MODE_MAX] = {
6631 [EXEC_UTMP_INIT] = "init",
6632 [EXEC_UTMP_LOGIN] = "login",
6633 [EXEC_UTMP_USER] = "user",
6634};
6635
6636DEFINE_STRING_TABLE_LOOKUP(exec_utmp_mode, ExecUtmpMode);
53f47dfc
YW
6637
6638static const char* const exec_preserve_mode_table[_EXEC_PRESERVE_MODE_MAX] = {
6639 [EXEC_PRESERVE_NO] = "no",
6640 [EXEC_PRESERVE_YES] = "yes",
6641 [EXEC_PRESERVE_RESTART] = "restart",
6642};
6643
6644DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(exec_preserve_mode, ExecPreserveMode, EXEC_PRESERVE_YES);
3536f49e 6645
6b7b2ed9 6646/* This table maps ExecDirectoryType to the setting it is configured with in the unit */
72fd1768 6647static const char* const exec_directory_type_table[_EXEC_DIRECTORY_TYPE_MAX] = {
3536f49e
YW
6648 [EXEC_DIRECTORY_RUNTIME] = "RuntimeDirectory",
6649 [EXEC_DIRECTORY_STATE] = "StateDirectory",
6650 [EXEC_DIRECTORY_CACHE] = "CacheDirectory",
6651 [EXEC_DIRECTORY_LOGS] = "LogsDirectory",
6652 [EXEC_DIRECTORY_CONFIGURATION] = "ConfigurationDirectory",
6653};
6654
6655DEFINE_STRING_TABLE_LOOKUP(exec_directory_type, ExecDirectoryType);
b1edf445 6656
6b7b2ed9
LP
6657/* And this table maps ExecDirectoryType too, but to a generic term identifying the type of resource. This
6658 * one is supposed to be generic enough to be used for unit types that don't use ExecContext and per-unit
6659 * directories, specifically .timer units with their timestamp touch file. */
6660static const char* const exec_resource_type_table[_EXEC_DIRECTORY_TYPE_MAX] = {
6661 [EXEC_DIRECTORY_RUNTIME] = "runtime",
6662 [EXEC_DIRECTORY_STATE] = "state",
6663 [EXEC_DIRECTORY_CACHE] = "cache",
6664 [EXEC_DIRECTORY_LOGS] = "logs",
6665 [EXEC_DIRECTORY_CONFIGURATION] = "configuration",
6666};
6667
6668DEFINE_STRING_TABLE_LOOKUP(exec_resource_type, ExecDirectoryType);
6669
6670/* And this table also maps ExecDirectoryType, to the environment variable we pass the selected directory to
6671 * the service payload in. */
fb2042dd
YW
6672static const char* const exec_directory_env_name_table[_EXEC_DIRECTORY_TYPE_MAX] = {
6673 [EXEC_DIRECTORY_RUNTIME] = "RUNTIME_DIRECTORY",
6674 [EXEC_DIRECTORY_STATE] = "STATE_DIRECTORY",
6675 [EXEC_DIRECTORY_CACHE] = "CACHE_DIRECTORY",
6676 [EXEC_DIRECTORY_LOGS] = "LOGS_DIRECTORY",
6677 [EXEC_DIRECTORY_CONFIGURATION] = "CONFIGURATION_DIRECTORY",
6678};
6679
6680DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(exec_directory_env_name, ExecDirectoryType);
6681
b1edf445
LP
6682static const char* const exec_keyring_mode_table[_EXEC_KEYRING_MODE_MAX] = {
6683 [EXEC_KEYRING_INHERIT] = "inherit",
6684 [EXEC_KEYRING_PRIVATE] = "private",
6685 [EXEC_KEYRING_SHARED] = "shared",
6686};
6687
6688DEFINE_STRING_TABLE_LOOKUP(exec_keyring_mode, ExecKeyringMode);