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