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