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