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