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