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