]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/execute.c
doc: minor hint about InaccessiblePaths= in regard of ProtectKernelTunables=
[thirdparty/systemd.git] / src / core / execute.c
CommitLineData
a7334b09
LP
1/***
2 This file is part of systemd.
3
4 Copyright 2010 Lennart Poettering
5
6 systemd is free software; you can redistribute it and/or modify it
5430f7f2
LP
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
a7334b09
LP
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
5430f7f2 14 Lesser General Public License for more details.
a7334b09 15
5430f7f2 16 You should have received a copy of the GNU Lesser General Public License
a7334b09
LP
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18***/
19
034c6ed7
LP
20#include <errno.h>
21#include <fcntl.h>
8dd4c05b
LP
22#include <glob.h>
23#include <grp.h>
24#include <poll.h>
309bff19 25#include <signal.h>
8dd4c05b 26#include <string.h>
19c0b0b9 27#include <sys/capability.h>
d251207d 28#include <sys/eventfd.h>
f3e43635 29#include <sys/mman.h>
8dd4c05b 30#include <sys/personality.h>
94f04347 31#include <sys/prctl.h>
8dd4c05b 32#include <sys/socket.h>
451a074f 33#include <sys/stat.h>
8dd4c05b
LP
34#include <sys/un.h>
35#include <unistd.h>
023a4f67 36#include <utmpx.h>
5cb5a6ff 37
5b6319dc
LP
38#ifdef HAVE_PAM
39#include <security/pam_appl.h>
40#endif
41
7b52a628
MS
42#ifdef HAVE_SELINUX
43#include <selinux/selinux.h>
44#endif
45
17df7223
LP
46#ifdef HAVE_SECCOMP
47#include <seccomp.h>
48#endif
49
eef65bf3
MS
50#ifdef HAVE_APPARMOR
51#include <sys/apparmor.h>
52#endif
53
24882e06 54#include "sd-messages.h"
8dd4c05b
LP
55
56#include "af-list.h"
b5efdb8a 57#include "alloc-util.h"
3ffd4af2
LP
58#ifdef HAVE_APPARMOR
59#include "apparmor-util.h"
60#endif
8dd4c05b
LP
61#include "async.h"
62#include "barrier.h"
8dd4c05b 63#include "cap-list.h"
430f0182 64#include "capability-util.h"
f6a6225e 65#include "def.h"
4d1a6904 66#include "env-util.h"
17df7223 67#include "errno-list.h"
3ffd4af2 68#include "execute.h"
8dd4c05b 69#include "exit-status.h"
3ffd4af2 70#include "fd-util.h"
8dd4c05b 71#include "fileio.h"
6482f626 72#include "formats-util.h"
f4f15635 73#include "fs-util.h"
7d50b32a 74#include "glob-util.h"
c004493c 75#include "io-util.h"
8dd4c05b
LP
76#include "ioprio.h"
77#include "log.h"
78#include "macro.h"
79#include "missing.h"
80#include "mkdir.h"
81#include "namespace.h"
6bedfcbb 82#include "parse-util.h"
8dd4c05b 83#include "path-util.h"
0b452006 84#include "process-util.h"
78f22b97 85#include "rlimit-util.h"
8dd4c05b 86#include "rm-rf.h"
3ffd4af2
LP
87#ifdef HAVE_SECCOMP
88#include "seccomp-util.h"
89#endif
8dd4c05b
LP
90#include "securebits.h"
91#include "selinux-util.h"
24882e06 92#include "signal-util.h"
8dd4c05b 93#include "smack-util.h"
fd63e712 94#include "special.h"
8b43440b 95#include "string-table.h"
07630cea 96#include "string-util.h"
8dd4c05b 97#include "strv.h"
7ccbd1ae 98#include "syslog-util.h"
8dd4c05b
LP
99#include "terminal-util.h"
100#include "unit.h"
b1d4f8e1 101#include "user-util.h"
8dd4c05b
LP
102#include "util.h"
103#include "utmp-wtmp.h"
5cb5a6ff 104
e056b01d 105#define IDLE_TIMEOUT_USEC (5*USEC_PER_SEC)
31a7eb86 106#define IDLE_TIMEOUT2_USEC (1*USEC_PER_SEC)
e6a26745 107
02a51aba
LP
108/* This assumes there is a 'tty' group */
109#define TTY_MODE 0620
110
531dca78
LP
111#define SNDBUF_SIZE (8*1024*1024)
112
034c6ed7
LP
113static int shift_fds(int fds[], unsigned n_fds) {
114 int start, restart_from;
115
116 if (n_fds <= 0)
117 return 0;
118
a0d40ac5
LP
119 /* Modifies the fds array! (sorts it) */
120
034c6ed7
LP
121 assert(fds);
122
123 start = 0;
124 for (;;) {
125 int i;
126
127 restart_from = -1;
128
129 for (i = start; i < (int) n_fds; i++) {
130 int nfd;
131
132 /* Already at right index? */
133 if (fds[i] == i+3)
134 continue;
135
3cc2aff1
LP
136 nfd = fcntl(fds[i], F_DUPFD, i + 3);
137 if (nfd < 0)
034c6ed7
LP
138 return -errno;
139
03e334a1 140 safe_close(fds[i]);
034c6ed7
LP
141 fds[i] = nfd;
142
143 /* Hmm, the fd we wanted isn't free? Then
ee33e53a 144 * let's remember that and try again from here */
034c6ed7
LP
145 if (nfd != i+3 && restart_from < 0)
146 restart_from = i;
147 }
148
149 if (restart_from < 0)
150 break;
151
152 start = restart_from;
153 }
154
155 return 0;
156}
157
c2748801 158static int flags_fds(const int fds[], unsigned n_fds, bool nonblock) {
47a71eed 159 unsigned i;
e2c76839 160 int r;
47a71eed
LP
161
162 if (n_fds <= 0)
163 return 0;
164
165 assert(fds);
166
451a074f 167 /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags */
47a71eed
LP
168
169 for (i = 0; i < n_fds; i++) {
47a71eed 170
3cc2aff1
LP
171 r = fd_nonblock(fds[i], nonblock);
172 if (r < 0)
e2c76839 173 return r;
47a71eed 174
451a074f
LP
175 /* We unconditionally drop FD_CLOEXEC from the fds,
176 * since after all we want to pass these fds to our
177 * children */
47a71eed 178
3cc2aff1
LP
179 r = fd_cloexec(fds[i], false);
180 if (r < 0)
e2c76839 181 return r;
47a71eed
LP
182 }
183
184 return 0;
185}
186
1e22b5cd 187static const char *exec_context_tty_path(const ExecContext *context) {
80876c20
LP
188 assert(context);
189
1e22b5cd
LP
190 if (context->stdio_as_fds)
191 return NULL;
192
80876c20
LP
193 if (context->tty_path)
194 return context->tty_path;
195
196 return "/dev/console";
197}
198
1e22b5cd
LP
199static void exec_context_tty_reset(const ExecContext *context, const ExecParameters *p) {
200 const char *path;
201
6ea832a2
LP
202 assert(context);
203
1e22b5cd 204 path = exec_context_tty_path(context);
6ea832a2 205
1e22b5cd
LP
206 if (context->tty_vhangup) {
207 if (p && p->stdin_fd >= 0)
208 (void) terminal_vhangup_fd(p->stdin_fd);
209 else if (path)
210 (void) terminal_vhangup(path);
211 }
6ea832a2 212
1e22b5cd
LP
213 if (context->tty_reset) {
214 if (p && p->stdin_fd >= 0)
215 (void) reset_terminal_fd(p->stdin_fd, true);
216 else if (path)
217 (void) reset_terminal(path);
218 }
219
220 if (context->tty_vt_disallocate && path)
221 (void) vt_disallocate(path);
6ea832a2
LP
222}
223
6af760f3
LP
224static bool is_terminal_input(ExecInput i) {
225 return IN_SET(i,
226 EXEC_INPUT_TTY,
227 EXEC_INPUT_TTY_FORCE,
228 EXEC_INPUT_TTY_FAIL);
229}
230
3a1286b6 231static bool is_terminal_output(ExecOutput o) {
6af760f3
LP
232 return IN_SET(o,
233 EXEC_OUTPUT_TTY,
234 EXEC_OUTPUT_SYSLOG_AND_CONSOLE,
235 EXEC_OUTPUT_KMSG_AND_CONSOLE,
236 EXEC_OUTPUT_JOURNAL_AND_CONSOLE);
237}
238
239static bool exec_context_needs_term(const ExecContext *c) {
240 assert(c);
241
242 /* Return true if the execution context suggests we should set $TERM to something useful. */
243
244 if (is_terminal_input(c->std_input))
245 return true;
246
247 if (is_terminal_output(c->std_output))
248 return true;
249
250 if (is_terminal_output(c->std_error))
251 return true;
252
253 return !!c->tty_path;
3a1286b6
MS
254}
255
80876c20
LP
256static int open_null_as(int flags, int nfd) {
257 int fd, r;
071830ff 258
80876c20 259 assert(nfd >= 0);
071830ff 260
613b411c
LP
261 fd = open("/dev/null", flags|O_NOCTTY);
262 if (fd < 0)
071830ff
LP
263 return -errno;
264
80876c20
LP
265 if (fd != nfd) {
266 r = dup2(fd, nfd) < 0 ? -errno : nfd;
03e334a1 267 safe_close(fd);
80876c20
LP
268 } else
269 r = nfd;
071830ff 270
80876c20 271 return r;
071830ff
LP
272}
273
524daa8c 274static int connect_journal_socket(int fd, uid_t uid, gid_t gid) {
b92bea5d
ZJS
275 union sockaddr_union sa = {
276 .un.sun_family = AF_UNIX,
277 .un.sun_path = "/run/systemd/journal/stdout",
278 };
524daa8c
ZJS
279 uid_t olduid = UID_INVALID;
280 gid_t oldgid = GID_INVALID;
281 int r;
282
283 if (gid != GID_INVALID) {
284 oldgid = getgid();
285
286 r = setegid(gid);
287 if (r < 0)
288 return -errno;
289 }
290
291 if (uid != UID_INVALID) {
292 olduid = getuid();
293
294 r = seteuid(uid);
295 if (r < 0) {
296 r = -errno;
297 goto restore_gid;
298 }
299 }
300
fc2fffe7 301 r = connect(fd, &sa.sa, SOCKADDR_UN_LEN(sa.un));
524daa8c
ZJS
302 if (r < 0)
303 r = -errno;
304
305 /* If we fail to restore the uid or gid, things will likely
306 fail later on. This should only happen if an LSM interferes. */
307
308 if (uid != UID_INVALID)
309 (void) seteuid(olduid);
310
311 restore_gid:
312 if (gid != GID_INVALID)
313 (void) setegid(oldgid);
314
315 return r;
316}
317
fd1f9c89 318static int connect_logger_as(
7a1ab780 319 Unit *unit,
fd1f9c89
LP
320 const ExecContext *context,
321 ExecOutput output,
322 const char *ident,
fd1f9c89
LP
323 int nfd,
324 uid_t uid,
325 gid_t gid) {
326
524daa8c 327 int fd, r;
071830ff
LP
328
329 assert(context);
80876c20
LP
330 assert(output < _EXEC_OUTPUT_MAX);
331 assert(ident);
332 assert(nfd >= 0);
071830ff 333
54fe0cdb
LP
334 fd = socket(AF_UNIX, SOCK_STREAM, 0);
335 if (fd < 0)
80876c20 336 return -errno;
071830ff 337
524daa8c
ZJS
338 r = connect_journal_socket(fd, uid, gid);
339 if (r < 0)
340 return r;
071830ff 341
80876c20 342 if (shutdown(fd, SHUT_RD) < 0) {
03e334a1 343 safe_close(fd);
80876c20
LP
344 return -errno;
345 }
071830ff 346
fd1f9c89 347 (void) fd_inc_sndbuf(fd, SNDBUF_SIZE);
531dca78 348
80876c20 349 dprintf(fd,
62bca2c6 350 "%s\n"
80876c20
LP
351 "%s\n"
352 "%i\n"
54fe0cdb
LP
353 "%i\n"
354 "%i\n"
355 "%i\n"
4f4a1dbf 356 "%i\n",
4f4a1dbf 357 context->syslog_identifier ? context->syslog_identifier : ident,
7a1ab780 358 unit->id,
54fe0cdb
LP
359 context->syslog_priority,
360 !!context->syslog_level_prefix,
361 output == EXEC_OUTPUT_SYSLOG || output == EXEC_OUTPUT_SYSLOG_AND_CONSOLE,
362 output == EXEC_OUTPUT_KMSG || output == EXEC_OUTPUT_KMSG_AND_CONSOLE,
3a1286b6 363 is_terminal_output(output));
80876c20 364
fd1f9c89
LP
365 if (fd == nfd)
366 return nfd;
367
368 r = dup2(fd, nfd) < 0 ? -errno : nfd;
369 safe_close(fd);
071830ff 370
80876c20
LP
371 return r;
372}
373static int open_terminal_as(const char *path, mode_t mode, int nfd) {
374 int fd, r;
071830ff 375
80876c20
LP
376 assert(path);
377 assert(nfd >= 0);
071830ff 378
3cc2aff1
LP
379 fd = open_terminal(path, mode | O_NOCTTY);
380 if (fd < 0)
80876c20 381 return fd;
071830ff 382
80876c20
LP
383 if (fd != nfd) {
384 r = dup2(fd, nfd) < 0 ? -errno : nfd;
03e334a1 385 safe_close(fd);
80876c20
LP
386 } else
387 r = nfd;
071830ff 388
80876c20
LP
389 return r;
390}
071830ff 391
1e3ad081
LP
392static int fixup_input(ExecInput std_input, int socket_fd, bool apply_tty_stdin) {
393
394 if (is_terminal_input(std_input) && !apply_tty_stdin)
395 return EXEC_INPUT_NULL;
071830ff 396
03fd9c49 397 if (std_input == EXEC_INPUT_SOCKET && socket_fd < 0)
4f2d528d
LP
398 return EXEC_INPUT_NULL;
399
03fd9c49 400 return std_input;
4f2d528d
LP
401}
402
03fd9c49 403static int fixup_output(ExecOutput std_output, int socket_fd) {
4f2d528d 404
03fd9c49 405 if (std_output == EXEC_OUTPUT_SOCKET && socket_fd < 0)
4f2d528d
LP
406 return EXEC_OUTPUT_INHERIT;
407
03fd9c49 408 return std_output;
4f2d528d
LP
409}
410
a34ceba6
LP
411static int setup_input(
412 const ExecContext *context,
413 const ExecParameters *params,
414 int socket_fd) {
415
4f2d528d
LP
416 ExecInput i;
417
418 assert(context);
a34ceba6
LP
419 assert(params);
420
421 if (params->stdin_fd >= 0) {
422 if (dup2(params->stdin_fd, STDIN_FILENO) < 0)
423 return -errno;
424
425 /* Try to make this the controlling tty, if it is a tty, and reset it */
426 (void) ioctl(STDIN_FILENO, TIOCSCTTY, context->std_input == EXEC_INPUT_TTY_FORCE);
427 (void) reset_terminal_fd(STDIN_FILENO, true);
428
429 return STDIN_FILENO;
430 }
4f2d528d 431
c39f1ce2 432 i = fixup_input(context->std_input, socket_fd, params->flags & EXEC_APPLY_TTY_STDIN);
4f2d528d
LP
433
434 switch (i) {
071830ff 435
80876c20
LP
436 case EXEC_INPUT_NULL:
437 return open_null_as(O_RDONLY, STDIN_FILENO);
438
439 case EXEC_INPUT_TTY:
440 case EXEC_INPUT_TTY_FORCE:
441 case EXEC_INPUT_TTY_FAIL: {
442 int fd, r;
071830ff 443
1e22b5cd 444 fd = acquire_terminal(exec_context_tty_path(context),
970edce6
ZJS
445 i == EXEC_INPUT_TTY_FAIL,
446 i == EXEC_INPUT_TTY_FORCE,
447 false,
3a43da28 448 USEC_INFINITY);
970edce6 449 if (fd < 0)
80876c20
LP
450 return fd;
451
452 if (fd != STDIN_FILENO) {
453 r = dup2(fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
03e334a1 454 safe_close(fd);
80876c20
LP
455 } else
456 r = STDIN_FILENO;
457
458 return r;
459 }
460
4f2d528d
LP
461 case EXEC_INPUT_SOCKET:
462 return dup2(socket_fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
463
80876c20
LP
464 default:
465 assert_not_reached("Unknown input type");
466 }
467}
468
a34ceba6
LP
469static int setup_output(
470 Unit *unit,
471 const ExecContext *context,
472 const ExecParameters *params,
473 int fileno,
474 int socket_fd,
475 const char *ident,
7bce046b
LP
476 uid_t uid,
477 gid_t gid,
478 dev_t *journal_stream_dev,
479 ino_t *journal_stream_ino) {
a34ceba6 480
4f2d528d
LP
481 ExecOutput o;
482 ExecInput i;
47c1d80d 483 int r;
4f2d528d 484
f2341e0a 485 assert(unit);
80876c20 486 assert(context);
a34ceba6 487 assert(params);
80876c20 488 assert(ident);
7bce046b
LP
489 assert(journal_stream_dev);
490 assert(journal_stream_ino);
80876c20 491
a34ceba6
LP
492 if (fileno == STDOUT_FILENO && params->stdout_fd >= 0) {
493
494 if (dup2(params->stdout_fd, STDOUT_FILENO) < 0)
495 return -errno;
496
497 return STDOUT_FILENO;
498 }
499
500 if (fileno == STDERR_FILENO && params->stderr_fd >= 0) {
501 if (dup2(params->stderr_fd, STDERR_FILENO) < 0)
502 return -errno;
503
504 return STDERR_FILENO;
505 }
506
c39f1ce2 507 i = fixup_input(context->std_input, socket_fd, params->flags & EXEC_APPLY_TTY_STDIN);
03fd9c49 508 o = fixup_output(context->std_output, socket_fd);
4f2d528d 509
eb17e935
MS
510 if (fileno == STDERR_FILENO) {
511 ExecOutput e;
512 e = fixup_output(context->std_error, socket_fd);
80876c20 513
eb17e935
MS
514 /* This expects the input and output are already set up */
515
516 /* Don't change the stderr file descriptor if we inherit all
517 * the way and are not on a tty */
518 if (e == EXEC_OUTPUT_INHERIT &&
519 o == EXEC_OUTPUT_INHERIT &&
520 i == EXEC_INPUT_NULL &&
521 !is_terminal_input(context->std_input) &&
522 getppid () != 1)
523 return fileno;
524
525 /* Duplicate from stdout if possible */
526 if (e == o || e == EXEC_OUTPUT_INHERIT)
527 return dup2(STDOUT_FILENO, fileno) < 0 ? -errno : fileno;
071830ff 528
eb17e935 529 o = e;
80876c20 530
eb17e935 531 } else if (o == EXEC_OUTPUT_INHERIT) {
21d21ea4
LP
532 /* If input got downgraded, inherit the original value */
533 if (i == EXEC_INPUT_NULL && is_terminal_input(context->std_input))
1e22b5cd 534 return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);
21d21ea4 535
acb591e4 536 /* If the input is connected to anything that's not a /dev/null, inherit that... */
ff876e28 537 if (i != EXEC_INPUT_NULL)
eb17e935 538 return dup2(STDIN_FILENO, fileno) < 0 ? -errno : fileno;
071830ff 539
acb591e4
LP
540 /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */
541 if (getppid() != 1)
eb17e935 542 return fileno;
94f04347 543
eb17e935
MS
544 /* We need to open /dev/null here anew, to get the right access mode. */
545 return open_null_as(O_WRONLY, fileno);
071830ff 546 }
94f04347 547
eb17e935 548 switch (o) {
80876c20
LP
549
550 case EXEC_OUTPUT_NULL:
eb17e935 551 return open_null_as(O_WRONLY, fileno);
80876c20
LP
552
553 case EXEC_OUTPUT_TTY:
4f2d528d 554 if (is_terminal_input(i))
eb17e935 555 return dup2(STDIN_FILENO, fileno) < 0 ? -errno : fileno;
80876c20
LP
556
557 /* We don't reset the terminal if this is just about output */
1e22b5cd 558 return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);
80876c20
LP
559
560 case EXEC_OUTPUT_SYSLOG:
28dbc1e8 561 case EXEC_OUTPUT_SYSLOG_AND_CONSOLE:
9a6bca7a 562 case EXEC_OUTPUT_KMSG:
28dbc1e8 563 case EXEC_OUTPUT_KMSG_AND_CONSOLE:
706343f4
LP
564 case EXEC_OUTPUT_JOURNAL:
565 case EXEC_OUTPUT_JOURNAL_AND_CONSOLE:
7a1ab780 566 r = connect_logger_as(unit, context, o, ident, fileno, uid, gid);
47c1d80d 567 if (r < 0) {
f2341e0a 568 log_unit_error_errno(unit, r, "Failed to connect %s to the journal socket, ignoring: %m", fileno == STDOUT_FILENO ? "stdout" : "stderr");
eb17e935 569 r = open_null_as(O_WRONLY, fileno);
7bce046b
LP
570 } else {
571 struct stat st;
572
573 /* If we connected this fd to the journal via a stream, patch the device/inode into the passed
574 * parameters, but only then. This is useful so that we can set $JOURNAL_STREAM that permits
575 * services to detect whether they are connected to the journal or not. */
576
577 if (fstat(fileno, &st) >= 0) {
578 *journal_stream_dev = st.st_dev;
579 *journal_stream_ino = st.st_ino;
580 }
47c1d80d
MS
581 }
582 return r;
4f2d528d
LP
583
584 case EXEC_OUTPUT_SOCKET:
585 assert(socket_fd >= 0);
eb17e935 586 return dup2(socket_fd, fileno) < 0 ? -errno : fileno;
94f04347
LP
587
588 default:
80876c20 589 assert_not_reached("Unknown error type");
94f04347 590 }
071830ff
LP
591}
592
02a51aba
LP
593static int chown_terminal(int fd, uid_t uid) {
594 struct stat st;
595
596 assert(fd >= 0);
02a51aba 597
1ff74fb6
LP
598 /* Before we chown/chmod the TTY, let's ensure this is actually a tty */
599 if (isatty(fd) < 1)
600 return 0;
601
02a51aba 602 /* This might fail. What matters are the results. */
bab45044
LP
603 (void) fchown(fd, uid, -1);
604 (void) fchmod(fd, TTY_MODE);
02a51aba
LP
605
606 if (fstat(fd, &st) < 0)
607 return -errno;
608
d8b4e2e9 609 if (st.st_uid != uid || (st.st_mode & 0777) != TTY_MODE)
02a51aba
LP
610 return -EPERM;
611
612 return 0;
613}
614
3d18b167
LP
615static int setup_confirm_stdio(int *_saved_stdin, int *_saved_stdout) {
616 _cleanup_close_ int fd = -1, saved_stdin = -1, saved_stdout = -1;
617 int r;
80876c20 618
80876c20
LP
619 assert(_saved_stdin);
620 assert(_saved_stdout);
621
af6da548
LP
622 saved_stdin = fcntl(STDIN_FILENO, F_DUPFD, 3);
623 if (saved_stdin < 0)
624 return -errno;
80876c20 625
af6da548 626 saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD, 3);
3d18b167
LP
627 if (saved_stdout < 0)
628 return -errno;
80876c20 629
af6da548
LP
630 fd = acquire_terminal(
631 "/dev/console",
632 false,
633 false,
634 false,
635 DEFAULT_CONFIRM_USEC);
3d18b167
LP
636 if (fd < 0)
637 return fd;
80876c20 638
af6da548
LP
639 r = chown_terminal(fd, getuid());
640 if (r < 0)
3d18b167 641 return r;
02a51aba 642
3d18b167
LP
643 r = reset_terminal_fd(fd, true);
644 if (r < 0)
645 return r;
80876c20 646
3d18b167
LP
647 if (dup2(fd, STDIN_FILENO) < 0)
648 return -errno;
649
650 if (dup2(fd, STDOUT_FILENO) < 0)
651 return -errno;
80876c20
LP
652
653 if (fd >= 2)
03e334a1 654 safe_close(fd);
3d18b167 655 fd = -1;
80876c20
LP
656
657 *_saved_stdin = saved_stdin;
658 *_saved_stdout = saved_stdout;
659
3d18b167 660 saved_stdin = saved_stdout = -1;
80876c20 661
3d18b167 662 return 0;
80876c20
LP
663}
664
44b601bc 665_printf_(1, 2) static int write_confirm_message(const char *format, ...) {
03e334a1 666 _cleanup_close_ int fd = -1;
af6da548 667 va_list ap;
80876c20 668
af6da548 669 assert(format);
80876c20 670
af6da548
LP
671 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
672 if (fd < 0)
673 return fd;
80876c20 674
af6da548
LP
675 va_start(ap, format);
676 vdprintf(fd, format, ap);
677 va_end(ap);
80876c20 678
af6da548
LP
679 return 0;
680}
80876c20 681
3d18b167 682static int restore_confirm_stdio(int *saved_stdin, int *saved_stdout) {
af6da548 683 int r = 0;
80876c20 684
af6da548
LP
685 assert(saved_stdin);
686 assert(saved_stdout);
687
688 release_terminal();
689
690 if (*saved_stdin >= 0)
80876c20 691 if (dup2(*saved_stdin, STDIN_FILENO) < 0)
af6da548 692 r = -errno;
80876c20 693
af6da548 694 if (*saved_stdout >= 0)
80876c20 695 if (dup2(*saved_stdout, STDOUT_FILENO) < 0)
af6da548 696 r = -errno;
80876c20 697
3d18b167
LP
698 *saved_stdin = safe_close(*saved_stdin);
699 *saved_stdout = safe_close(*saved_stdout);
af6da548
LP
700
701 return r;
702}
703
704static int ask_for_confirmation(char *response, char **argv) {
705 int saved_stdout = -1, saved_stdin = -1, r;
e1d75803 706 _cleanup_free_ char *line = NULL;
af6da548
LP
707
708 r = setup_confirm_stdio(&saved_stdin, &saved_stdout);
709 if (r < 0)
710 return r;
711
712 line = exec_command_line(argv);
713 if (!line)
714 return -ENOMEM;
715
418b9be5 716 r = ask_char(response, "yns", "Execute %s? [Yes, No, Skip] ", line);
af6da548
LP
717
718 restore_confirm_stdio(&saved_stdin, &saved_stdout);
719
720 return r;
80876c20
LP
721}
722
81a2b7ce
LP
723static int enforce_groups(const ExecContext *context, const char *username, gid_t gid) {
724 bool keep_groups = false;
725 int r;
726
727 assert(context);
728
35b8ca3a 729 /* Lookup and set GID and supplementary group list. Here too
81a2b7ce
LP
730 * we avoid NSS lookups for gid=0. */
731
732 if (context->group || username) {
81a2b7ce
LP
733 /* First step, initialize groups from /etc/groups */
734 if (username && gid != 0) {
735 if (initgroups(username, gid) < 0)
736 return -errno;
737
738 keep_groups = true;
739 }
740
741 /* Second step, set our gids */
742 if (setresgid(gid, gid, gid) < 0)
743 return -errno;
744 }
745
746 if (context->supplementary_groups) {
747 int ngroups_max, k;
748 gid_t *gids;
749 char **i;
750
751 /* Final step, initialize any manually set supplementary groups */
da19d5c1 752 assert_se((ngroups_max = (int) sysconf(_SC_NGROUPS_MAX)) > 0);
81a2b7ce
LP
753
754 if (!(gids = new(gid_t, ngroups_max)))
755 return -ENOMEM;
756
757 if (keep_groups) {
3cc2aff1
LP
758 k = getgroups(ngroups_max, gids);
759 if (k < 0) {
81a2b7ce
LP
760 free(gids);
761 return -errno;
762 }
763 } else
764 k = 0;
765
766 STRV_FOREACH(i, context->supplementary_groups) {
4b67834e 767 const char *g;
81a2b7ce
LP
768
769 if (k >= ngroups_max) {
770 free(gids);
771 return -E2BIG;
772 }
773
4b67834e
LP
774 g = *i;
775 r = get_group_creds(&g, gids+k);
776 if (r < 0) {
81a2b7ce
LP
777 free(gids);
778 return r;
779 }
780
781 k++;
782 }
783
97f0e76f
LP
784 r = maybe_setgroups(k, gids);
785 if (r < 0) {
81a2b7ce 786 free(gids);
97f0e76f 787 return r;
81a2b7ce
LP
788 }
789
790 free(gids);
791 }
792
793 return 0;
794}
795
796static int enforce_user(const ExecContext *context, uid_t uid) {
81a2b7ce
LP
797 assert(context);
798
479050b3 799 /* Sets (but doesn't look up) the uid and make sure we keep the
81a2b7ce
LP
800 * capabilities while doing so. */
801
479050b3 802 if (context->capability_ambient_set != 0) {
81a2b7ce
LP
803
804 /* First step: If we need to keep capabilities but
805 * drop privileges we need to make sure we keep our
cbb21cca 806 * caps, while we drop privileges. */
693ced48 807 if (uid != 0) {
cbb21cca 808 int sb = context->secure_bits | 1<<SECURE_KEEP_CAPS;
693ced48
LP
809
810 if (prctl(PR_GET_SECUREBITS) != sb)
811 if (prctl(PR_SET_SECUREBITS, sb) < 0)
812 return -errno;
813 }
81a2b7ce
LP
814 }
815
479050b3 816 /* Second step: actually set the uids */
81a2b7ce
LP
817 if (setresuid(uid, uid, uid) < 0)
818 return -errno;
819
820 /* At this point we should have all necessary capabilities but
821 are otherwise a normal user. However, the caps might got
822 corrupted due to the setresuid() so we need clean them up
823 later. This is done outside of this call. */
824
825 return 0;
826}
827
5b6319dc
LP
828#ifdef HAVE_PAM
829
830static int null_conv(
831 int num_msg,
832 const struct pam_message **msg,
833 struct pam_response **resp,
834 void *appdata_ptr) {
835
836 /* We don't support conversations */
837
838 return PAM_CONV_ERR;
839}
840
cefc33ae
LP
841#endif
842
5b6319dc
LP
843static int setup_pam(
844 const char *name,
845 const char *user,
940c5210 846 uid_t uid,
2d6fce8d 847 gid_t gid,
5b6319dc 848 const char *tty,
2065ca69 849 char ***env,
5b6319dc
LP
850 int fds[], unsigned n_fds) {
851
cefc33ae
LP
852#ifdef HAVE_PAM
853
5b6319dc
LP
854 static const struct pam_conv conv = {
855 .conv = null_conv,
856 .appdata_ptr = NULL
857 };
858
2d7c6aa2 859 _cleanup_(barrier_destroy) Barrier barrier = BARRIER_NULL;
5b6319dc 860 pam_handle_t *handle = NULL;
d6e5f3ad 861 sigset_t old_ss;
7bb70b6e 862 int pam_code = PAM_SUCCESS, r;
84eada2f 863 char **nv, **e = NULL;
5b6319dc
LP
864 bool close_session = false;
865 pid_t pam_pid = 0, parent_pid;
970edce6 866 int flags = 0;
5b6319dc
LP
867
868 assert(name);
869 assert(user);
2065ca69 870 assert(env);
5b6319dc
LP
871
872 /* We set up PAM in the parent process, then fork. The child
35b8ca3a 873 * will then stay around until killed via PR_GET_PDEATHSIG or
5b6319dc
LP
874 * systemd via the cgroup logic. It will then remove the PAM
875 * session again. The parent process will exec() the actual
876 * daemon. We do things this way to ensure that the main PID
877 * of the daemon is the one we initially fork()ed. */
878
7bb70b6e
LP
879 r = barrier_create(&barrier);
880 if (r < 0)
2d7c6aa2
DH
881 goto fail;
882
553d2243 883 if (log_get_max_level() < LOG_DEBUG)
970edce6
ZJS
884 flags |= PAM_SILENT;
885
f546241b
ZJS
886 pam_code = pam_start(name, user, &conv, &handle);
887 if (pam_code != PAM_SUCCESS) {
5b6319dc
LP
888 handle = NULL;
889 goto fail;
890 }
891
f546241b
ZJS
892 if (tty) {
893 pam_code = pam_set_item(handle, PAM_TTY, tty);
894 if (pam_code != PAM_SUCCESS)
5b6319dc 895 goto fail;
f546241b 896 }
5b6319dc 897
84eada2f
JW
898 STRV_FOREACH(nv, *env) {
899 pam_code = pam_putenv(handle, *nv);
2065ca69
JW
900 if (pam_code != PAM_SUCCESS)
901 goto fail;
902 }
903
970edce6 904 pam_code = pam_acct_mgmt(handle, flags);
f546241b 905 if (pam_code != PAM_SUCCESS)
5b6319dc
LP
906 goto fail;
907
970edce6 908 pam_code = pam_open_session(handle, flags);
f546241b 909 if (pam_code != PAM_SUCCESS)
5b6319dc
LP
910 goto fail;
911
912 close_session = true;
913
f546241b
ZJS
914 e = pam_getenvlist(handle);
915 if (!e) {
5b6319dc
LP
916 pam_code = PAM_BUF_ERR;
917 goto fail;
918 }
919
920 /* Block SIGTERM, so that we know that it won't get lost in
921 * the child */
ce30c8dc 922
72c0a2c2 923 assert_se(sigprocmask_many(SIG_BLOCK, &old_ss, SIGTERM, -1) >= 0);
5b6319dc
LP
924
925 parent_pid = getpid();
926
f546241b 927 pam_pid = fork();
7bb70b6e
LP
928 if (pam_pid < 0) {
929 r = -errno;
5b6319dc 930 goto fail;
7bb70b6e 931 }
5b6319dc
LP
932
933 if (pam_pid == 0) {
7bb70b6e 934 int sig, ret = EXIT_PAM;
5b6319dc
LP
935
936 /* The child's job is to reset the PAM session on
937 * termination */
2d7c6aa2 938 barrier_set_role(&barrier, BARRIER_CHILD);
5b6319dc
LP
939
940 /* This string must fit in 10 chars (i.e. the length
5d6b1584
LP
941 * of "/sbin/init"), to look pretty in /bin/ps */
942 rename_process("(sd-pam)");
5b6319dc
LP
943
944 /* Make sure we don't keep open the passed fds in this
945 child. We assume that otherwise only those fds are
946 open here that have been opened by PAM. */
947 close_many(fds, n_fds);
948
940c5210
AK
949 /* Drop privileges - we don't need any to pam_close_session
950 * and this will make PR_SET_PDEATHSIG work in most cases.
951 * If this fails, ignore the error - but expect sd-pam threads
952 * to fail to exit normally */
2d6fce8d 953
97f0e76f
LP
954 r = maybe_setgroups(0, NULL);
955 if (r < 0)
956 log_warning_errno(r, "Failed to setgroups() in sd-pam: %m");
2d6fce8d
LP
957 if (setresgid(gid, gid, gid) < 0)
958 log_warning_errno(errno, "Failed to setresgid() in sd-pam: %m");
940c5210 959 if (setresuid(uid, uid, uid) < 0)
2d6fce8d 960 log_warning_errno(errno, "Failed to setresuid() in sd-pam: %m");
940c5210 961
ce30c8dc
LP
962 (void) ignore_signals(SIGPIPE, -1);
963
940c5210
AK
964 /* Wait until our parent died. This will only work if
965 * the above setresuid() succeeds, otherwise the kernel
966 * will not allow unprivileged parents kill their privileged
967 * children this way. We rely on the control groups kill logic
5b6319dc
LP
968 * to do the rest for us. */
969 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
970 goto child_finish;
971
2d7c6aa2
DH
972 /* Tell the parent that our setup is done. This is especially
973 * important regarding dropping privileges. Otherwise, unit
974 * setup might race against our setresuid(2) call. */
975 barrier_place(&barrier);
976
5b6319dc
LP
977 /* Check if our parent process might already have
978 * died? */
979 if (getppid() == parent_pid) {
d6e5f3ad
DM
980 sigset_t ss;
981
982 assert_se(sigemptyset(&ss) >= 0);
983 assert_se(sigaddset(&ss, SIGTERM) >= 0);
984
3dead8d9
LP
985 for (;;) {
986 if (sigwait(&ss, &sig) < 0) {
987 if (errno == EINTR)
988 continue;
989
990 goto child_finish;
991 }
5b6319dc 992
3dead8d9
LP
993 assert(sig == SIGTERM);
994 break;
995 }
5b6319dc
LP
996 }
997
3dead8d9 998 /* If our parent died we'll end the session */
f546241b 999 if (getppid() != parent_pid) {
970edce6 1000 pam_code = pam_close_session(handle, flags);
f546241b 1001 if (pam_code != PAM_SUCCESS)
5b6319dc 1002 goto child_finish;
f546241b 1003 }
5b6319dc 1004
7bb70b6e 1005 ret = 0;
5b6319dc
LP
1006
1007 child_finish:
970edce6 1008 pam_end(handle, pam_code | flags);
7bb70b6e 1009 _exit(ret);
5b6319dc
LP
1010 }
1011
2d7c6aa2
DH
1012 barrier_set_role(&barrier, BARRIER_PARENT);
1013
5b6319dc
LP
1014 /* If the child was forked off successfully it will do all the
1015 * cleanups, so forget about the handle here. */
1016 handle = NULL;
1017
3b8bddde 1018 /* Unblock SIGTERM again in the parent */
72c0a2c2 1019 assert_se(sigprocmask(SIG_SETMASK, &old_ss, NULL) >= 0);
5b6319dc
LP
1020
1021 /* We close the log explicitly here, since the PAM modules
1022 * might have opened it, but we don't want this fd around. */
1023 closelog();
1024
2d7c6aa2
DH
1025 /* Synchronously wait for the child to initialize. We don't care for
1026 * errors as we cannot recover. However, warn loudly if it happens. */
1027 if (!barrier_place_and_sync(&barrier))
1028 log_error("PAM initialization failed");
1029
2065ca69
JW
1030 strv_free(*env);
1031 *env = e;
aa87e624 1032
5b6319dc
LP
1033 return 0;
1034
1035fail:
970edce6
ZJS
1036 if (pam_code != PAM_SUCCESS) {
1037 log_error("PAM failed: %s", pam_strerror(handle, pam_code));
7bb70b6e
LP
1038 r = -EPERM; /* PAM errors do not map to errno */
1039 } else
1040 log_error_errno(r, "PAM failed: %m");
9ba35398 1041
5b6319dc
LP
1042 if (handle) {
1043 if (close_session)
970edce6 1044 pam_code = pam_close_session(handle, flags);
5b6319dc 1045
970edce6 1046 pam_end(handle, pam_code | flags);
5b6319dc
LP
1047 }
1048
1049 strv_free(e);
5b6319dc
LP
1050 closelog();
1051
7bb70b6e 1052 return r;
cefc33ae
LP
1053#else
1054 return 0;
5b6319dc 1055#endif
cefc33ae 1056}
5b6319dc 1057
5d6b1584
LP
1058static void rename_process_from_path(const char *path) {
1059 char process_name[11];
1060 const char *p;
1061 size_t l;
1062
1063 /* This resulting string must fit in 10 chars (i.e. the length
1064 * of "/sbin/init") to look pretty in /bin/ps */
1065
2b6bf07d 1066 p = basename(path);
5d6b1584
LP
1067 if (isempty(p)) {
1068 rename_process("(...)");
1069 return;
1070 }
1071
1072 l = strlen(p);
1073 if (l > 8) {
1074 /* The end of the process name is usually more
1075 * interesting, since the first bit might just be
1076 * "systemd-" */
1077 p = p + l - 8;
1078 l = 8;
1079 }
1080
1081 process_name[0] = '(';
1082 memcpy(process_name+1, p, l);
1083 process_name[1+l] = ')';
1084 process_name[1+l+1] = 0;
1085
1086 rename_process(process_name);
1087}
1088
c0467cf3 1089#ifdef HAVE_SECCOMP
17df7223 1090
83f12b27
FS
1091static bool skip_seccomp_unavailable(const Unit* u, const char* msg) {
1092 if (!is_seccomp_available()) {
1093 log_open();
d347d902 1094 log_unit_debug(u, "SECCOMP features not detected in the kernel, skipping %s", msg);
83f12b27
FS
1095 log_close();
1096 return true;
1097 }
1098 return false;
1099}
1100
1101static int apply_seccomp(const Unit* u, const ExecContext *c) {
17df7223
LP
1102 uint32_t negative_action, action;
1103 scmp_filter_ctx *seccomp;
c0467cf3
RC
1104 Iterator i;
1105 void *id;
17df7223 1106 int r;
8351ceae 1107
c0467cf3 1108 assert(c);
8351ceae 1109
83f12b27
FS
1110 if (skip_seccomp_unavailable(u, "syscall filtering"))
1111 return 0;
1112
17df7223
LP
1113 negative_action = c->syscall_errno == 0 ? SCMP_ACT_KILL : SCMP_ACT_ERRNO(c->syscall_errno);
1114
1115 seccomp = seccomp_init(c->syscall_whitelist ? negative_action : SCMP_ACT_ALLOW);
1116 if (!seccomp)
1117 return -ENOMEM;
8351ceae 1118
e9642be2
LP
1119 if (c->syscall_archs) {
1120
1121 SET_FOREACH(id, c->syscall_archs, i) {
1122 r = seccomp_arch_add(seccomp, PTR_TO_UINT32(id) - 1);
1123 if (r == -EEXIST)
1124 continue;
7c66bae2
LP
1125 if (r < 0)
1126 goto finish;
e9642be2 1127 }
e9642be2 1128
7c66bae2 1129 } else {
e9642be2 1130 r = seccomp_add_secondary_archs(seccomp);
7c66bae2
LP
1131 if (r < 0)
1132 goto finish;
57183d11 1133 }
8351ceae 1134
57183d11 1135 action = c->syscall_whitelist ? SCMP_ACT_ALLOW : negative_action;
17df7223
LP
1136 SET_FOREACH(id, c->syscall_filter, i) {
1137 r = seccomp_rule_add(seccomp, action, PTR_TO_INT(id) - 1, 0);
7c66bae2
LP
1138 if (r < 0)
1139 goto finish;
c0467cf3 1140 }
8351ceae 1141
7c66bae2
LP
1142 r = seccomp_attr_set(seccomp, SCMP_FLTATR_CTL_NNP, 0);
1143 if (r < 0)
1144 goto finish;
1145
17df7223 1146 r = seccomp_load(seccomp);
7c66bae2
LP
1147
1148finish:
17df7223 1149 seccomp_release(seccomp);
4298d0b5
LP
1150 return r;
1151}
1152
83f12b27 1153static int apply_address_families(const Unit* u, const ExecContext *c) {
4298d0b5
LP
1154 scmp_filter_ctx *seccomp;
1155 Iterator i;
1156 int r;
1157
1158 assert(c);
1159
83f12b27
FS
1160 if (skip_seccomp_unavailable(u, "RestrictAddressFamilies="))
1161 return 0;
1162
4298d0b5
LP
1163 seccomp = seccomp_init(SCMP_ACT_ALLOW);
1164 if (!seccomp)
1165 return -ENOMEM;
1166
1167 r = seccomp_add_secondary_archs(seccomp);
1168 if (r < 0)
1169 goto finish;
1170
1171 if (c->address_families_whitelist) {
1172 int af, first = 0, last = 0;
1173 void *afp;
1174
1175 /* If this is a whitelist, we first block the address
1176 * families that are out of range and then everything
1177 * that is not in the set. First, we find the lowest
1178 * and highest address family in the set. */
1179
1180 SET_FOREACH(afp, c->address_families, i) {
1181 af = PTR_TO_INT(afp);
17df7223 1182
4298d0b5
LP
1183 if (af <= 0 || af >= af_max())
1184 continue;
1185
1186 if (first == 0 || af < first)
1187 first = af;
1188
1189 if (last == 0 || af > last)
1190 last = af;
1191 }
1192
1193 assert((first == 0) == (last == 0));
1194
1195 if (first == 0) {
1196
1197 /* No entries in the valid range, block everything */
1198 r = seccomp_rule_add(
1199 seccomp,
1200 SCMP_ACT_ERRNO(EPROTONOSUPPORT),
1201 SCMP_SYS(socket),
1202 0);
1203 if (r < 0)
1204 goto finish;
1205
1206 } else {
1207
1208 /* Block everything below the first entry */
1209 r = seccomp_rule_add(
1210 seccomp,
1211 SCMP_ACT_ERRNO(EPROTONOSUPPORT),
1212 SCMP_SYS(socket),
1213 1,
1214 SCMP_A0(SCMP_CMP_LT, first));
1215 if (r < 0)
1216 goto finish;
1217
1218 /* Block everything above the last entry */
1219 r = seccomp_rule_add(
1220 seccomp,
1221 SCMP_ACT_ERRNO(EPROTONOSUPPORT),
1222 SCMP_SYS(socket),
1223 1,
1224 SCMP_A0(SCMP_CMP_GT, last));
1225 if (r < 0)
1226 goto finish;
1227
1228 /* Block everything between the first and last
1229 * entry */
1230 for (af = 1; af < af_max(); af++) {
1231
1232 if (set_contains(c->address_families, INT_TO_PTR(af)))
1233 continue;
1234
1235 r = seccomp_rule_add(
1236 seccomp,
1237 SCMP_ACT_ERRNO(EPROTONOSUPPORT),
1238 SCMP_SYS(socket),
1239 1,
1240 SCMP_A0(SCMP_CMP_EQ, af));
1241 if (r < 0)
1242 goto finish;
1243 }
1244 }
1245
1246 } else {
1247 void *af;
1248
1249 /* If this is a blacklist, then generate one rule for
1250 * each address family that are then combined in OR
1251 * checks. */
1252
1253 SET_FOREACH(af, c->address_families, i) {
1254
1255 r = seccomp_rule_add(
1256 seccomp,
1257 SCMP_ACT_ERRNO(EPROTONOSUPPORT),
1258 SCMP_SYS(socket),
1259 1,
1260 SCMP_A0(SCMP_CMP_EQ, PTR_TO_INT(af)));
1261 if (r < 0)
1262 goto finish;
1263 }
1264 }
1265
1266 r = seccomp_attr_set(seccomp, SCMP_FLTATR_CTL_NNP, 0);
1267 if (r < 0)
1268 goto finish;
1269
1270 r = seccomp_load(seccomp);
1271
1272finish:
1273 seccomp_release(seccomp);
17df7223 1274 return r;
8351ceae 1275}
4298d0b5 1276
83f12b27 1277static int apply_memory_deny_write_execute(const Unit* u, const ExecContext *c) {
f3e43635
TM
1278 scmp_filter_ctx *seccomp;
1279 int r;
1280
1281 assert(c);
1282
83f12b27
FS
1283 if (skip_seccomp_unavailable(u, "MemoryDenyWriteExecute="))
1284 return 0;
1285
f3e43635
TM
1286 seccomp = seccomp_init(SCMP_ACT_ALLOW);
1287 if (!seccomp)
1288 return -ENOMEM;
1289
72246c2a
LP
1290 r = seccomp_add_secondary_archs(seccomp);
1291 if (r < 0)
1292 goto finish;
1293
f3e43635
TM
1294 r = seccomp_rule_add(
1295 seccomp,
abd84d4d 1296 SCMP_ACT_ERRNO(EPERM),
f3e43635
TM
1297 SCMP_SYS(mmap),
1298 1,
1299 SCMP_A2(SCMP_CMP_MASKED_EQ, PROT_EXEC|PROT_WRITE, PROT_EXEC|PROT_WRITE));
1300 if (r < 0)
1301 goto finish;
1302
1303 r = seccomp_rule_add(
1304 seccomp,
abd84d4d 1305 SCMP_ACT_ERRNO(EPERM),
f3e43635
TM
1306 SCMP_SYS(mprotect),
1307 1,
1308 SCMP_A2(SCMP_CMP_MASKED_EQ, PROT_EXEC, PROT_EXEC));
1309 if (r < 0)
1310 goto finish;
1311
1312 r = seccomp_attr_set(seccomp, SCMP_FLTATR_CTL_NNP, 0);
1313 if (r < 0)
1314 goto finish;
1315
1316 r = seccomp_load(seccomp);
1317
1318finish:
1319 seccomp_release(seccomp);
1320 return r;
1321}
1322
83f12b27 1323static int apply_restrict_realtime(const Unit* u, const ExecContext *c) {
f4170c67
LP
1324 static const int permitted_policies[] = {
1325 SCHED_OTHER,
1326 SCHED_BATCH,
1327 SCHED_IDLE,
1328 };
1329
1330 scmp_filter_ctx *seccomp;
1331 unsigned i;
1332 int r, p, max_policy = 0;
1333
1334 assert(c);
1335
83f12b27
FS
1336 if (skip_seccomp_unavailable(u, "RestrictRealtime="))
1337 return 0;
1338
f4170c67
LP
1339 seccomp = seccomp_init(SCMP_ACT_ALLOW);
1340 if (!seccomp)
1341 return -ENOMEM;
1342
72246c2a
LP
1343 r = seccomp_add_secondary_archs(seccomp);
1344 if (r < 0)
1345 goto finish;
1346
f4170c67
LP
1347 /* Determine the highest policy constant we want to allow */
1348 for (i = 0; i < ELEMENTSOF(permitted_policies); i++)
1349 if (permitted_policies[i] > max_policy)
1350 max_policy = permitted_policies[i];
1351
1352 /* Go through all policies with lower values than that, and block them -- unless they appear in the
1353 * whitelist. */
1354 for (p = 0; p < max_policy; p++) {
1355 bool good = false;
1356
1357 /* Check if this is in the whitelist. */
1358 for (i = 0; i < ELEMENTSOF(permitted_policies); i++)
1359 if (permitted_policies[i] == p) {
1360 good = true;
1361 break;
1362 }
1363
1364 if (good)
1365 continue;
1366
1367 /* Deny this policy */
1368 r = seccomp_rule_add(
1369 seccomp,
1370 SCMP_ACT_ERRNO(EPERM),
1371 SCMP_SYS(sched_setscheduler),
1372 1,
1373 SCMP_A1(SCMP_CMP_EQ, p));
1374 if (r < 0)
1375 goto finish;
1376 }
1377
1378 /* Blacklist all other policies, i.e. the ones with higher values. Note that all comparisons are unsigned here,
1379 * hence no need no check for < 0 values. */
1380 r = seccomp_rule_add(
1381 seccomp,
1382 SCMP_ACT_ERRNO(EPERM),
1383 SCMP_SYS(sched_setscheduler),
1384 1,
1385 SCMP_A1(SCMP_CMP_GT, max_policy));
1386 if (r < 0)
1387 goto finish;
1388
1389 r = seccomp_attr_set(seccomp, SCMP_FLTATR_CTL_NNP, 0);
1390 if (r < 0)
1391 goto finish;
1392
1393 r = seccomp_load(seccomp);
1394
1395finish:
1396 seccomp_release(seccomp);
1397 return r;
1398}
1399
59eeb84b
LP
1400static int apply_protect_sysctl(Unit *u, const ExecContext *c) {
1401 scmp_filter_ctx *seccomp;
1402 int r;
1403
1404 assert(c);
1405
1406 /* Turn off the legacy sysctl() system call. Many distributions turn this off while building the kernel, but
1407 * let's protect even those systems where this is left on in the kernel. */
1408
1409 if (skip_seccomp_unavailable(u, "ProtectKernelTunables="))
1410 return 0;
1411
1412 seccomp = seccomp_init(SCMP_ACT_ALLOW);
1413 if (!seccomp)
1414 return -ENOMEM;
1415
1416 r = seccomp_add_secondary_archs(seccomp);
1417 if (r < 0)
1418 goto finish;
1419
1420 r = seccomp_rule_add(
1421 seccomp,
1422 SCMP_ACT_ERRNO(EPERM),
1423 SCMP_SYS(_sysctl),
1424 0);
1425 if (r < 0)
1426 goto finish;
1427
1428 r = seccomp_attr_set(seccomp, SCMP_FLTATR_CTL_NNP, 0);
1429 if (r < 0)
1430 goto finish;
1431
1432 r = seccomp_load(seccomp);
1433
1434finish:
1435 seccomp_release(seccomp);
1436 return r;
1437}
1438
502d704e
DH
1439static int apply_protect_kernel_modules(Unit *u, const ExecContext *c) {
1440 static const int module_syscalls[] = {
1441 SCMP_SYS(delete_module),
1442 SCMP_SYS(finit_module),
1443 SCMP_SYS(init_module),
1444 };
1445
1446 scmp_filter_ctx *seccomp;
1447 unsigned i;
1448 int r;
1449
1450 assert(c);
1451
1452 /* Turn of module syscalls on ProtectKernelModules=yes */
1453
1454 if (skip_seccomp_unavailable(u, "ProtectKernelModules="))
1455 return 0;
1456
1457 seccomp = seccomp_init(SCMP_ACT_ALLOW);
1458 if (!seccomp)
1459 return -ENOMEM;
1460
1461 r = seccomp_add_secondary_archs(seccomp);
1462 if (r < 0)
1463 goto finish;
1464
1465 for (i = 0; i < ELEMENTSOF(module_syscalls); i++) {
1466 r = seccomp_rule_add(seccomp, SCMP_ACT_ERRNO(EPERM),
1467 module_syscalls[i], 0);
1468 if (r < 0)
1469 goto finish;
1470 }
1471
1472 r = seccomp_attr_set(seccomp, SCMP_FLTATR_CTL_NNP, 0);
1473 if (r < 0)
1474 goto finish;
1475
1476 r = seccomp_load(seccomp);
1477
1478finish:
1479 seccomp_release(seccomp);
1480 return r;
1481}
1482
ba128bb8 1483static int apply_private_devices(Unit *u, const ExecContext *c) {
8f81a5f6 1484 const SystemCallFilterSet *set;
ba128bb8 1485 scmp_filter_ctx *seccomp;
8f81a5f6
DH
1486 const char *sys;
1487 bool syscalls_found = false;
ba128bb8
LP
1488 int r;
1489
1490 assert(c);
1491
8f81a5f6 1492 /* If PrivateDevices= is set, also turn off iopl and all @raw-io syscalls. */
ba128bb8
LP
1493
1494 if (skip_seccomp_unavailable(u, "PrivateDevices="))
1495 return 0;
1496
1497 seccomp = seccomp_init(SCMP_ACT_ALLOW);
1498 if (!seccomp)
1499 return -ENOMEM;
1500
1501 r = seccomp_add_secondary_archs(seccomp);
1502 if (r < 0)
1503 goto finish;
1504
8f81a5f6
DH
1505 for (set = syscall_filter_sets; set->set_name; set++)
1506 if (streq(set->set_name, "@raw-io")) {
1507 syscalls_found = true;
1508 break;
1509 }
1510
1511 /* We should never fail here */
1512 if (!syscalls_found) {
1513 r = -EOPNOTSUPP;
1514 goto finish;
1515 }
1516
1517 NULSTR_FOREACH(sys, set->value) {
1518 int id;
1519 bool add = true;
1520
1521#ifndef __NR_s390_pci_mmio_read
1522 if (streq(sys, "s390_pci_mmio_read"))
1523 add = false;
1524#endif
1525#ifndef __NR_s390_pci_mmio_write
1526 if (streq(sys, "s390_pci_mmio_write"))
1527 add = false;
1528#endif
1529
1530 if (!add)
1531 continue;
1532
1533 id = seccomp_syscall_resolve_name(sys);
1534
ba128bb8
LP
1535 r = seccomp_rule_add(
1536 seccomp,
1537 SCMP_ACT_ERRNO(EPERM),
8f81a5f6 1538 id, 0);
ba128bb8
LP
1539 if (r < 0)
1540 goto finish;
1541 }
1542
1543 r = seccomp_attr_set(seccomp, SCMP_FLTATR_CTL_NNP, 0);
1544 if (r < 0)
1545 goto finish;
1546
1547 r = seccomp_load(seccomp);
1548
1549finish:
1550 seccomp_release(seccomp);
1551 return r;
1552}
1553
c0467cf3 1554#endif
8351ceae 1555
31a7eb86
ZJS
1556static void do_idle_pipe_dance(int idle_pipe[4]) {
1557 assert(idle_pipe);
1558
54eb2300
LP
1559 idle_pipe[1] = safe_close(idle_pipe[1]);
1560 idle_pipe[2] = safe_close(idle_pipe[2]);
31a7eb86
ZJS
1561
1562 if (idle_pipe[0] >= 0) {
1563 int r;
1564
1565 r = fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT_USEC);
1566
1567 if (idle_pipe[3] >= 0 && r == 0 /* timeout */) {
c7cc737f
LP
1568 ssize_t n;
1569
31a7eb86 1570 /* Signal systemd that we are bored and want to continue. */
c7cc737f
LP
1571 n = write(idle_pipe[3], "x", 1);
1572 if (n > 0)
cd972d69
ZJS
1573 /* Wait for systemd to react to the signal above. */
1574 fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT2_USEC);
31a7eb86
ZJS
1575 }
1576
54eb2300 1577 idle_pipe[0] = safe_close(idle_pipe[0]);
31a7eb86
ZJS
1578
1579 }
1580
54eb2300 1581 idle_pipe[3] = safe_close(idle_pipe[3]);
31a7eb86
ZJS
1582}
1583
7cae38c4 1584static int build_environment(
fd63e712 1585 Unit *u,
9fa95f85 1586 const ExecContext *c,
1e22b5cd 1587 const ExecParameters *p,
7cae38c4
LP
1588 unsigned n_fds,
1589 const char *home,
1590 const char *username,
1591 const char *shell,
7bce046b
LP
1592 dev_t journal_stream_dev,
1593 ino_t journal_stream_ino,
7cae38c4
LP
1594 char ***ret) {
1595
1596 _cleanup_strv_free_ char **our_env = NULL;
1597 unsigned n_env = 0;
1598 char *x;
1599
4b58153d 1600 assert(u);
7cae38c4
LP
1601 assert(c);
1602 assert(ret);
1603
4b58153d 1604 our_env = new0(char*, 14);
7cae38c4
LP
1605 if (!our_env)
1606 return -ENOMEM;
1607
1608 if (n_fds > 0) {
8dd4c05b
LP
1609 _cleanup_free_ char *joined = NULL;
1610
ccd06097 1611 if (asprintf(&x, "LISTEN_PID="PID_FMT, getpid()) < 0)
7cae38c4
LP
1612 return -ENOMEM;
1613 our_env[n_env++] = x;
1614
1615 if (asprintf(&x, "LISTEN_FDS=%u", n_fds) < 0)
1616 return -ENOMEM;
1617 our_env[n_env++] = x;
8dd4c05b 1618
1e22b5cd 1619 joined = strv_join(p->fd_names, ":");
8dd4c05b
LP
1620 if (!joined)
1621 return -ENOMEM;
1622
1623 x = strjoin("LISTEN_FDNAMES=", joined, NULL);
1624 if (!x)
1625 return -ENOMEM;
1626 our_env[n_env++] = x;
7cae38c4
LP
1627 }
1628
b08af3b1 1629 if ((p->flags & EXEC_SET_WATCHDOG) && p->watchdog_usec > 0) {
ccd06097 1630 if (asprintf(&x, "WATCHDOG_PID="PID_FMT, getpid()) < 0)
09812eb7
LP
1631 return -ENOMEM;
1632 our_env[n_env++] = x;
1633
1e22b5cd 1634 if (asprintf(&x, "WATCHDOG_USEC="USEC_FMT, p->watchdog_usec) < 0)
09812eb7
LP
1635 return -ENOMEM;
1636 our_env[n_env++] = x;
1637 }
1638
fd63e712
LP
1639 /* If this is D-Bus, tell the nss-systemd module, since it relies on being able to use D-Bus look up dynamic
1640 * users via PID 1, possibly dead-locking the dbus daemon. This way it will not use D-Bus to resolve names, but
1641 * check the database directly. */
1642 if (unit_has_name(u, SPECIAL_DBUS_SERVICE)) {
1643 x = strdup("SYSTEMD_NSS_BYPASS_BUS=1");
1644 if (!x)
1645 return -ENOMEM;
1646 our_env[n_env++] = x;
1647 }
1648
7cae38c4
LP
1649 if (home) {
1650 x = strappend("HOME=", home);
1651 if (!x)
1652 return -ENOMEM;
1653 our_env[n_env++] = x;
1654 }
1655
1656 if (username) {
1657 x = strappend("LOGNAME=", username);
1658 if (!x)
1659 return -ENOMEM;
1660 our_env[n_env++] = x;
1661
1662 x = strappend("USER=", username);
1663 if (!x)
1664 return -ENOMEM;
1665 our_env[n_env++] = x;
1666 }
1667
1668 if (shell) {
1669 x = strappend("SHELL=", shell);
1670 if (!x)
1671 return -ENOMEM;
1672 our_env[n_env++] = x;
1673 }
1674
4b58153d
LP
1675 if (!sd_id128_is_null(u->invocation_id)) {
1676 if (asprintf(&x, "INVOCATION_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(u->invocation_id)) < 0)
1677 return -ENOMEM;
1678
1679 our_env[n_env++] = x;
1680 }
1681
6af760f3
LP
1682 if (exec_context_needs_term(c)) {
1683 const char *tty_path, *term = NULL;
1684
1685 tty_path = exec_context_tty_path(c);
1686
1687 /* If we are forked off PID 1 and we are supposed to operate on /dev/console, then let's try to inherit
1688 * the $TERM set for PID 1. This is useful for containers so that the $TERM the container manager
1689 * passes to PID 1 ends up all the way in the console login shown. */
1690
1691 if (path_equal(tty_path, "/dev/console") && getppid() == 1)
1692 term = getenv("TERM");
1693 if (!term)
1694 term = default_term_for_tty(tty_path);
7cae38c4 1695
6af760f3 1696 x = strappend("TERM=", term);
7cae38c4
LP
1697 if (!x)
1698 return -ENOMEM;
1699 our_env[n_env++] = x;
1700 }
1701
7bce046b
LP
1702 if (journal_stream_dev != 0 && journal_stream_ino != 0) {
1703 if (asprintf(&x, "JOURNAL_STREAM=" DEV_FMT ":" INO_FMT, journal_stream_dev, journal_stream_ino) < 0)
1704 return -ENOMEM;
1705
1706 our_env[n_env++] = x;
1707 }
1708
7cae38c4 1709 our_env[n_env++] = NULL;
7bce046b 1710 assert(n_env <= 12);
7cae38c4
LP
1711
1712 *ret = our_env;
1713 our_env = NULL;
1714
1715 return 0;
1716}
1717
b4c14404
FB
1718static int build_pass_environment(const ExecContext *c, char ***ret) {
1719 _cleanup_strv_free_ char **pass_env = NULL;
1720 size_t n_env = 0, n_bufsize = 0;
1721 char **i;
1722
1723 STRV_FOREACH(i, c->pass_environment) {
1724 _cleanup_free_ char *x = NULL;
1725 char *v;
1726
1727 v = getenv(*i);
1728 if (!v)
1729 continue;
1730 x = strjoin(*i, "=", v, NULL);
1731 if (!x)
1732 return -ENOMEM;
1733 if (!GREEDY_REALLOC(pass_env, n_bufsize, n_env + 2))
1734 return -ENOMEM;
1735 pass_env[n_env++] = x;
1736 pass_env[n_env] = NULL;
1737 x = NULL;
1738 }
1739
1740 *ret = pass_env;
1741 pass_env = NULL;
1742
1743 return 0;
1744}
1745
8b44a3d2
LP
1746static bool exec_needs_mount_namespace(
1747 const ExecContext *context,
1748 const ExecParameters *params,
1749 ExecRuntime *runtime) {
1750
1751 assert(context);
1752 assert(params);
1753
2a624c36
AP
1754 if (!strv_isempty(context->read_write_paths) ||
1755 !strv_isempty(context->read_only_paths) ||
1756 !strv_isempty(context->inaccessible_paths))
8b44a3d2
LP
1757 return true;
1758
1759 if (context->mount_flags != 0)
1760 return true;
1761
1762 if (context->private_tmp && runtime && (runtime->tmp_dir || runtime->var_tmp_dir))
1763 return true;
1764
8b44a3d2
LP
1765 if (context->private_devices ||
1766 context->protect_system != PROTECT_SYSTEM_NO ||
59eeb84b
LP
1767 context->protect_home != PROTECT_HOME_NO ||
1768 context->protect_kernel_tunables ||
1769 context->protect_control_groups)
8b44a3d2
LP
1770 return true;
1771
1772 return false;
1773}
1774
d251207d
LP
1775static int setup_private_users(uid_t uid, gid_t gid) {
1776 _cleanup_free_ char *uid_map = NULL, *gid_map = NULL;
1777 _cleanup_close_pair_ int errno_pipe[2] = { -1, -1 };
1778 _cleanup_close_ int unshare_ready_fd = -1;
1779 _cleanup_(sigkill_waitp) pid_t pid = 0;
1780 uint64_t c = 1;
1781 siginfo_t si;
1782 ssize_t n;
1783 int r;
1784
1785 /* Set up a user namespace and map root to root, the selected UID/GID to itself, and everything else to
1786 * nobody. In order to be able to write this mapping we need CAP_SETUID in the original user namespace, which
1787 * we however lack after opening the user namespace. To work around this we fork() a temporary child process,
1788 * which waits for the parent to create the new user namespace while staying in the original namespace. The
1789 * child then writes the UID mapping, under full privileges. The parent waits for the child to finish and
1790 * continues execution normally. */
1791
1792 if (uid != 0 && uid_is_valid(uid))
1793 asprintf(&uid_map,
1794 "0 0 1\n" /* Map root → root */
1795 UID_FMT " " UID_FMT " 1\n", /* Map $UID → $UID */
1796 uid, uid); /* The case where the above is the same */
1797 else
1798 uid_map = strdup("0 0 1\n");
1799 if (!uid_map)
1800 return -ENOMEM;
1801
1802 if (gid != 0 && gid_is_valid(gid))
1803 asprintf(&gid_map,
1804 "0 0 1\n" /* Map root → root */
1805 GID_FMT " " GID_FMT " 1\n", /* Map $GID → $GID */
1806 gid, gid);
1807 else
1808 gid_map = strdup("0 0 1\n"); /* The case where the above is the same */
1809 if (!gid_map)
1810 return -ENOMEM;
1811
1812 /* Create a communication channel so that the parent can tell the child when it finished creating the user
1813 * namespace. */
1814 unshare_ready_fd = eventfd(0, EFD_CLOEXEC);
1815 if (unshare_ready_fd < 0)
1816 return -errno;
1817
1818 /* Create a communication channel so that the child can tell the parent a proper error code in case it
1819 * failed. */
1820 if (pipe2(errno_pipe, O_CLOEXEC) < 0)
1821 return -errno;
1822
1823 pid = fork();
1824 if (pid < 0)
1825 return -errno;
1826
1827 if (pid == 0) {
1828 _cleanup_close_ int fd = -1;
1829 const char *a;
1830 pid_t ppid;
1831
1832 /* Child process, running in the original user namespace. Let's update the parent's UID/GID map from
1833 * here, after the parent opened its own user namespace. */
1834
1835 ppid = getppid();
1836 errno_pipe[0] = safe_close(errno_pipe[0]);
1837
1838 /* Wait until the parent unshared the user namespace */
1839 if (read(unshare_ready_fd, &c, sizeof(c)) < 0) {
1840 r = -errno;
1841 goto child_fail;
1842 }
1843
1844 /* Disable the setgroups() system call in the child user namespace, for good. */
1845 a = procfs_file_alloca(ppid, "setgroups");
1846 fd = open(a, O_WRONLY|O_CLOEXEC);
1847 if (fd < 0) {
1848 if (errno != ENOENT) {
1849 r = -errno;
1850 goto child_fail;
1851 }
1852
1853 /* If the file is missing the kernel is too old, let's continue anyway. */
1854 } else {
1855 if (write(fd, "deny\n", 5) < 0) {
1856 r = -errno;
1857 goto child_fail;
1858 }
1859
1860 fd = safe_close(fd);
1861 }
1862
1863 /* First write the GID map */
1864 a = procfs_file_alloca(ppid, "gid_map");
1865 fd = open(a, O_WRONLY|O_CLOEXEC);
1866 if (fd < 0) {
1867 r = -errno;
1868 goto child_fail;
1869 }
1870 if (write(fd, gid_map, strlen(gid_map)) < 0) {
1871 r = -errno;
1872 goto child_fail;
1873 }
1874 fd = safe_close(fd);
1875
1876 /* The write the UID map */
1877 a = procfs_file_alloca(ppid, "uid_map");
1878 fd = open(a, O_WRONLY|O_CLOEXEC);
1879 if (fd < 0) {
1880 r = -errno;
1881 goto child_fail;
1882 }
1883 if (write(fd, uid_map, strlen(uid_map)) < 0) {
1884 r = -errno;
1885 goto child_fail;
1886 }
1887
1888 _exit(EXIT_SUCCESS);
1889
1890 child_fail:
1891 (void) write(errno_pipe[1], &r, sizeof(r));
1892 _exit(EXIT_FAILURE);
1893 }
1894
1895 errno_pipe[1] = safe_close(errno_pipe[1]);
1896
1897 if (unshare(CLONE_NEWUSER) < 0)
1898 return -errno;
1899
1900 /* Let the child know that the namespace is ready now */
1901 if (write(unshare_ready_fd, &c, sizeof(c)) < 0)
1902 return -errno;
1903
1904 /* Try to read an error code from the child */
1905 n = read(errno_pipe[0], &r, sizeof(r));
1906 if (n < 0)
1907 return -errno;
1908 if (n == sizeof(r)) { /* an error code was sent to us */
1909 if (r < 0)
1910 return r;
1911 return -EIO;
1912 }
1913 if (n != 0) /* on success we should have read 0 bytes */
1914 return -EIO;
1915
1916 r = wait_for_terminate(pid, &si);
1917 if (r < 0)
1918 return r;
1919 pid = 0;
1920
1921 /* If something strange happened with the child, let's consider this fatal, too */
1922 if (si.si_code != CLD_EXITED || si.si_status != 0)
1923 return -EIO;
1924
1925 return 0;
1926}
1927
07689d5d
LP
1928static int setup_runtime_directory(
1929 const ExecContext *context,
1930 const ExecParameters *params,
1931 uid_t uid,
1932 gid_t gid) {
1933
1934 char **rt;
1935 int r;
1936
1937 assert(context);
1938 assert(params);
1939
1940 STRV_FOREACH(rt, context->runtime_directory) {
1941 _cleanup_free_ char *p;
1942
1943 p = strjoin(params->runtime_prefix, "/", *rt, NULL);
1944 if (!p)
1945 return -ENOMEM;
1946
1947 r = mkdir_p_label(p, context->runtime_directory_mode);
1948 if (r < 0)
1949 return r;
1950
1951 r = chmod_and_chown(p, context->runtime_directory_mode, uid, gid);
1952 if (r < 0)
1953 return r;
1954 }
1955
1956 return 0;
1957}
1958
cefc33ae
LP
1959static int setup_smack(
1960 const ExecContext *context,
1961 const ExecCommand *command) {
1962
1963#ifdef HAVE_SMACK
1964 int r;
1965
1966 assert(context);
1967 assert(command);
1968
1969 if (!mac_smack_use())
1970 return 0;
1971
1972 if (context->smack_process_label) {
1973 r = mac_smack_apply_pid(0, context->smack_process_label);
1974 if (r < 0)
1975 return r;
1976 }
1977#ifdef SMACK_DEFAULT_PROCESS_LABEL
1978 else {
1979 _cleanup_free_ char *exec_label = NULL;
1980
1981 r = mac_smack_read(command->path, SMACK_ATTR_EXEC, &exec_label);
1982 if (r < 0 && r != -ENODATA && r != -EOPNOTSUPP)
1983 return r;
1984
1985 r = mac_smack_apply_pid(0, exec_label ? : SMACK_DEFAULT_PROCESS_LABEL);
1986 if (r < 0)
1987 return r;
1988 }
1989#endif
1990#endif
1991
1992 return 0;
1993}
1994
3fbe8dbe
LP
1995static int compile_read_write_paths(
1996 const ExecContext *context,
1997 const ExecParameters *params,
1998 char ***ret) {
1999
2000 _cleanup_strv_free_ char **l = NULL;
2001 char **rt;
2002
2003 /* Compile the list of writable paths. This is the combination of the explicitly configured paths, plus all
2004 * runtime directories. */
2005
2006 if (strv_isempty(context->read_write_paths) &&
2007 strv_isempty(context->runtime_directory)) {
2008 *ret = NULL; /* NOP if neither is set */
2009 return 0;
2010 }
2011
2012 l = strv_copy(context->read_write_paths);
2013 if (!l)
2014 return -ENOMEM;
2015
2016 STRV_FOREACH(rt, context->runtime_directory) {
2017 char *s;
2018
2019 s = strjoin(params->runtime_prefix, "/", *rt, NULL);
2020 if (!s)
2021 return -ENOMEM;
2022
2023 if (strv_consume(&l, s) < 0)
2024 return -ENOMEM;
2025 }
2026
2027 *ret = l;
2028 l = NULL;
2029
2030 return 0;
2031}
2032
29206d46
LP
2033static void append_socket_pair(int *array, unsigned *n, int pair[2]) {
2034 assert(array);
2035 assert(n);
2036
2037 if (!pair)
2038 return;
2039
2040 if (pair[0] >= 0)
2041 array[(*n)++] = pair[0];
2042 if (pair[1] >= 0)
2043 array[(*n)++] = pair[1];
2044}
2045
a34ceba6
LP
2046static int close_remaining_fds(
2047 const ExecParameters *params,
2048 ExecRuntime *runtime,
29206d46 2049 DynamicCreds *dcreds,
00d9ef85 2050 int user_lookup_fd,
a34ceba6
LP
2051 int socket_fd,
2052 int *fds, unsigned n_fds) {
2053
2054 unsigned n_dont_close = 0;
00d9ef85 2055 int dont_close[n_fds + 12];
a34ceba6
LP
2056
2057 assert(params);
2058
2059 if (params->stdin_fd >= 0)
2060 dont_close[n_dont_close++] = params->stdin_fd;
2061 if (params->stdout_fd >= 0)
2062 dont_close[n_dont_close++] = params->stdout_fd;
2063 if (params->stderr_fd >= 0)
2064 dont_close[n_dont_close++] = params->stderr_fd;
2065
2066 if (socket_fd >= 0)
2067 dont_close[n_dont_close++] = socket_fd;
2068 if (n_fds > 0) {
2069 memcpy(dont_close + n_dont_close, fds, sizeof(int) * n_fds);
2070 n_dont_close += n_fds;
2071 }
2072
29206d46
LP
2073 if (runtime)
2074 append_socket_pair(dont_close, &n_dont_close, runtime->netns_storage_socket);
2075
2076 if (dcreds) {
2077 if (dcreds->user)
2078 append_socket_pair(dont_close, &n_dont_close, dcreds->user->storage_socket);
2079 if (dcreds->group)
2080 append_socket_pair(dont_close, &n_dont_close, dcreds->group->storage_socket);
a34ceba6
LP
2081 }
2082
00d9ef85
LP
2083 if (user_lookup_fd >= 0)
2084 dont_close[n_dont_close++] = user_lookup_fd;
2085
a34ceba6
LP
2086 return close_all_fds(dont_close, n_dont_close);
2087}
2088
59eeb84b
LP
2089static bool context_has_address_families(const ExecContext *c) {
2090 assert(c);
2091
2092 return c->address_families_whitelist ||
2093 !set_isempty(c->address_families);
2094}
2095
2096static bool context_has_syscall_filters(const ExecContext *c) {
2097 assert(c);
2098
2099 return c->syscall_whitelist ||
2100 !set_isempty(c->syscall_filter) ||
2101 !set_isempty(c->syscall_archs);
2102}
2103
2104static bool context_has_no_new_privileges(const ExecContext *c) {
2105 assert(c);
2106
2107 if (c->no_new_privileges)
2108 return true;
2109
2110 if (have_effective_cap(CAP_SYS_ADMIN)) /* if we are privileged, we don't need NNP */
2111 return false;
2112
2113 return context_has_address_families(c) || /* we need NNP if we have any form of seccomp and are unprivileged */
2114 c->memory_deny_write_execute ||
2115 c->restrict_realtime ||
2116 c->protect_kernel_tunables ||
2117 context_has_syscall_filters(c);
2118}
2119
00d9ef85
LP
2120static int send_user_lookup(
2121 Unit *unit,
2122 int user_lookup_fd,
2123 uid_t uid,
2124 gid_t gid) {
2125
2126 assert(unit);
2127
2128 /* Send the resolved UID/GID to PID 1 after we learnt it. We send a single datagram, containing the UID/GID
2129 * data as well as the unit name. Note that we suppress sending this if no user/group to resolve was
2130 * specified. */
2131
2132 if (user_lookup_fd < 0)
2133 return 0;
2134
2135 if (!uid_is_valid(uid) && !gid_is_valid(gid))
2136 return 0;
2137
2138 if (writev(user_lookup_fd,
2139 (struct iovec[]) {
2140 { .iov_base = &uid, .iov_len = sizeof(uid) },
2141 { .iov_base = &gid, .iov_len = sizeof(gid) },
2142 { .iov_base = unit->id, .iov_len = strlen(unit->id) }}, 3) < 0)
2143 return -errno;
2144
2145 return 0;
2146}
2147
ff0af2a1 2148static int exec_child(
f2341e0a 2149 Unit *unit,
ff0af2a1
LP
2150 ExecCommand *command,
2151 const ExecContext *context,
2152 const ExecParameters *params,
2153 ExecRuntime *runtime,
29206d46 2154 DynamicCreds *dcreds,
ff0af2a1
LP
2155 char **argv,
2156 int socket_fd,
2157 int *fds, unsigned n_fds,
2158 char **files_env,
00d9ef85 2159 int user_lookup_fd,
ff0af2a1 2160 int *exit_status) {
d35fbf6b 2161
2065ca69 2162 _cleanup_strv_free_ char **our_env = NULL, **pass_env = NULL, **accum_env = NULL, **final_argv = NULL;
9008e1ac 2163 _cleanup_free_ char *mac_selinux_context_net = NULL;
5f5d8eab 2164 const char *username = NULL, *home = NULL, *shell = NULL, *wd;
7bce046b
LP
2165 dev_t journal_stream_dev = 0;
2166 ino_t journal_stream_ino = 0;
2167 bool needs_mount_namespace;
fed1e721
LP
2168 uid_t uid = UID_INVALID;
2169 gid_t gid = GID_INVALID;
ff0af2a1 2170 int i, r;
034c6ed7 2171
f2341e0a 2172 assert(unit);
5cb5a6ff
LP
2173 assert(command);
2174 assert(context);
d35fbf6b 2175 assert(params);
ff0af2a1 2176 assert(exit_status);
d35fbf6b
DM
2177
2178 rename_process_from_path(command->path);
2179
2180 /* We reset exactly these signals, since they are the
2181 * only ones we set to SIG_IGN in the main daemon. All
2182 * others we leave untouched because we set them to
2183 * SIG_DFL or a valid handler initially, both of which
2184 * will be demoted to SIG_DFL. */
ce30c8dc
LP
2185 (void) default_signals(SIGNALS_CRASH_HANDLER,
2186 SIGNALS_IGNORE, -1);
d35fbf6b
DM
2187
2188 if (context->ignore_sigpipe)
ce30c8dc 2189 (void) ignore_signals(SIGPIPE, -1);
d35fbf6b 2190
ff0af2a1
LP
2191 r = reset_signal_mask();
2192 if (r < 0) {
2193 *exit_status = EXIT_SIGNAL_MASK;
2194 return r;
d35fbf6b 2195 }
034c6ed7 2196
d35fbf6b
DM
2197 if (params->idle_pipe)
2198 do_idle_pipe_dance(params->idle_pipe);
4f2d528d 2199
d35fbf6b
DM
2200 /* Close sockets very early to make sure we don't
2201 * block init reexecution because it cannot bind its
2202 * sockets */
ff0af2a1 2203
d35fbf6b 2204 log_forget_fds();
4f2d528d 2205
00d9ef85 2206 r = close_remaining_fds(params, runtime, dcreds, user_lookup_fd, socket_fd, fds, n_fds);
ff0af2a1
LP
2207 if (r < 0) {
2208 *exit_status = EXIT_FDS;
2209 return r;
8c7be95e
LP
2210 }
2211
d35fbf6b
DM
2212 if (!context->same_pgrp)
2213 if (setsid() < 0) {
ff0af2a1 2214 *exit_status = EXIT_SETSID;
d35fbf6b
DM
2215 return -errno;
2216 }
9e2f7c11 2217
1e22b5cd 2218 exec_context_tty_reset(context, params);
d35fbf6b 2219
c39f1ce2 2220 if (params->flags & EXEC_CONFIRM_SPAWN) {
d35fbf6b
DM
2221 char response;
2222
ff0af2a1
LP
2223 r = ask_for_confirmation(&response, argv);
2224 if (r == -ETIMEDOUT)
d35fbf6b 2225 write_confirm_message("Confirmation question timed out, assuming positive response.\n");
ff0af2a1
LP
2226 else if (r < 0)
2227 write_confirm_message("Couldn't ask confirmation question, assuming positive response: %s\n", strerror(-r));
d35fbf6b
DM
2228 else if (response == 's') {
2229 write_confirm_message("Skipping execution.\n");
ff0af2a1 2230 *exit_status = EXIT_CONFIRM;
d35fbf6b
DM
2231 return -ECANCELED;
2232 } else if (response == 'n') {
2233 write_confirm_message("Failing execution.\n");
ff0af2a1 2234 *exit_status = 0;
d35fbf6b
DM
2235 return 0;
2236 }
2237 }
1a63a750 2238
29206d46
LP
2239 if (context->dynamic_user && dcreds) {
2240
409093fe
LP
2241 /* Make sure we bypass our own NSS module for any NSS checks */
2242 if (putenv((char*) "SYSTEMD_NSS_DYNAMIC_BYPASS=1") != 0) {
2243 *exit_status = EXIT_USER;
2244 return -errno;
2245 }
2246
29206d46 2247 r = dynamic_creds_realize(dcreds, &uid, &gid);
ff0af2a1
LP
2248 if (r < 0) {
2249 *exit_status = EXIT_USER;
2250 return r;
524daa8c 2251 }
524daa8c 2252
92b25bca 2253 if (!uid_is_valid(uid) || !gid_is_valid(gid)) {
29206d46
LP
2254 *exit_status = EXIT_USER;
2255 return -ESRCH;
2256 }
5bc7452b 2257
29206d46
LP
2258 if (dcreds->user)
2259 username = dcreds->user->name;
2260
2261 } else {
2262 if (context->user) {
2263 username = context->user;
be39ccf3 2264 r = get_user_creds_clean(&username, &uid, &gid, &home, &shell);
29206d46
LP
2265 if (r < 0) {
2266 *exit_status = EXIT_USER;
2267 return r;
2268 }
70493828 2269
629ff674 2270 /* Note that we don't set $HOME or $SHELL if they are not particularly enlightening anyway
be39ccf3 2271 * (i.e. are "/" or "/bin/nologin"). */
5bc7452b 2272 }
5bc7452b 2273
29206d46
LP
2274 if (context->group) {
2275 const char *g = context->group;
2276
2277 r = get_group_creds(&g, &gid);
2278 if (r < 0) {
2279 *exit_status = EXIT_GROUP;
2280 return r;
2281 }
2282 }
2283 }
5bc7452b 2284
00d9ef85
LP
2285 r = send_user_lookup(unit, user_lookup_fd, uid, gid);
2286 if (r < 0) {
2287 *exit_status = EXIT_USER;
2288 return r;
2289 }
2290
2291 user_lookup_fd = safe_close(user_lookup_fd);
2292
d35fbf6b
DM
2293 /* If a socket is connected to STDIN/STDOUT/STDERR, we
2294 * must sure to drop O_NONBLOCK */
2295 if (socket_fd >= 0)
a34ceba6 2296 (void) fd_nonblock(socket_fd, false);
acbb0225 2297
a34ceba6 2298 r = setup_input(context, params, socket_fd);
ff0af2a1
LP
2299 if (r < 0) {
2300 *exit_status = EXIT_STDIN;
2301 return r;
d35fbf6b 2302 }
034c6ed7 2303
7bce046b 2304 r = setup_output(unit, context, params, STDOUT_FILENO, socket_fd, basename(command->path), uid, gid, &journal_stream_dev, &journal_stream_ino);
ff0af2a1
LP
2305 if (r < 0) {
2306 *exit_status = EXIT_STDOUT;
2307 return r;
d35fbf6b
DM
2308 }
2309
7bce046b 2310 r = setup_output(unit, context, params, STDERR_FILENO, socket_fd, basename(command->path), uid, gid, &journal_stream_dev, &journal_stream_ino);
ff0af2a1
LP
2311 if (r < 0) {
2312 *exit_status = EXIT_STDERR;
2313 return r;
d35fbf6b
DM
2314 }
2315
2316 if (params->cgroup_path) {
ff0af2a1
LP
2317 r = cg_attach_everywhere(params->cgroup_supported, params->cgroup_path, 0, NULL, NULL);
2318 if (r < 0) {
2319 *exit_status = EXIT_CGROUP;
2320 return r;
309bff19 2321 }
d35fbf6b 2322 }
309bff19 2323
d35fbf6b 2324 if (context->oom_score_adjust_set) {
d5243d62 2325 char t[DECIMAL_STR_MAX(context->oom_score_adjust)];
f2b68789 2326
d5243d62
LP
2327 /* When we can't make this change due to EPERM, then
2328 * let's silently skip over it. User namespaces
2329 * prohibit write access to this file, and we
2330 * shouldn't trip up over that. */
613b411c 2331
d5243d62 2332 sprintf(t, "%i", context->oom_score_adjust);
ad118bda 2333 r = write_string_file("/proc/self/oom_score_adj", t, 0);
6cb7fa17 2334 if (r == -EPERM || r == -EACCES) {
ff0af2a1 2335 log_open();
f2341e0a 2336 log_unit_debug_errno(unit, r, "Failed to adjust OOM setting, assuming containerized execution, ignoring: %m");
ff0af2a1
LP
2337 log_close();
2338 } else if (r < 0) {
2339 *exit_status = EXIT_OOM_ADJUST;
d35fbf6b 2340 return -errno;
613b411c 2341 }
d35fbf6b
DM
2342 }
2343
2344 if (context->nice_set)
2345 if (setpriority(PRIO_PROCESS, 0, context->nice) < 0) {
ff0af2a1 2346 *exit_status = EXIT_NICE;
d35fbf6b 2347 return -errno;
613b411c
LP
2348 }
2349
d35fbf6b
DM
2350 if (context->cpu_sched_set) {
2351 struct sched_param param = {
2352 .sched_priority = context->cpu_sched_priority,
2353 };
2354
ff0af2a1
LP
2355 r = sched_setscheduler(0,
2356 context->cpu_sched_policy |
2357 (context->cpu_sched_reset_on_fork ?
2358 SCHED_RESET_ON_FORK : 0),
2359 &param);
2360 if (r < 0) {
2361 *exit_status = EXIT_SETSCHEDULER;
d35fbf6b 2362 return -errno;
fc9b2a84 2363 }
d35fbf6b 2364 }
fc9b2a84 2365
d35fbf6b
DM
2366 if (context->cpuset)
2367 if (sched_setaffinity(0, CPU_ALLOC_SIZE(context->cpuset_ncpus), context->cpuset) < 0) {
ff0af2a1 2368 *exit_status = EXIT_CPUAFFINITY;
d35fbf6b 2369 return -errno;
034c6ed7
LP
2370 }
2371
d35fbf6b
DM
2372 if (context->ioprio_set)
2373 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
ff0af2a1 2374 *exit_status = EXIT_IOPRIO;
d35fbf6b
DM
2375 return -errno;
2376 }
da726a4d 2377
d35fbf6b
DM
2378 if (context->timer_slack_nsec != NSEC_INFINITY)
2379 if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
ff0af2a1 2380 *exit_status = EXIT_TIMERSLACK;
d35fbf6b 2381 return -errno;
4c2630eb 2382 }
9eba9da4 2383
050f7277 2384 if (context->personality != PERSONALITY_INVALID)
d35fbf6b 2385 if (personality(context->personality) < 0) {
ff0af2a1 2386 *exit_status = EXIT_PERSONALITY;
d35fbf6b 2387 return -errno;
4c2630eb 2388 }
94f04347 2389
d35fbf6b 2390 if (context->utmp_id)
023a4f67
LP
2391 utmp_put_init_process(context->utmp_id, getpid(), getsid(0), context->tty_path,
2392 context->utmp_mode == EXEC_UTMP_INIT ? INIT_PROCESS :
2393 context->utmp_mode == EXEC_UTMP_LOGIN ? LOGIN_PROCESS :
2394 USER_PROCESS,
2395 username ? "root" : context->user);
d35fbf6b 2396
e0d2adfd 2397 if (context->user) {
ff0af2a1
LP
2398 r = chown_terminal(STDIN_FILENO, uid);
2399 if (r < 0) {
2400 *exit_status = EXIT_STDIN;
2401 return r;
071830ff 2402 }
d35fbf6b 2403 }
8e274523 2404
a931ad47
LP
2405 /* If delegation is enabled we'll pass ownership of the cgroup
2406 * (but only in systemd's own controller hierarchy!) to the
2407 * user of the new process. */
2408 if (params->cgroup_path && context->user && params->cgroup_delegate) {
ff0af2a1
LP
2409 r = cg_set_task_access(SYSTEMD_CGROUP_CONTROLLER, params->cgroup_path, 0644, uid, gid);
2410 if (r < 0) {
2411 *exit_status = EXIT_CGROUP;
2412 return r;
d35fbf6b 2413 }
034c6ed7 2414
034c6ed7 2415
ff0af2a1
LP
2416 r = cg_set_group_access(SYSTEMD_CGROUP_CONTROLLER, params->cgroup_path, 0755, uid, gid);
2417 if (r < 0) {
2418 *exit_status = EXIT_CGROUP;
2419 return r;
034c6ed7 2420 }
d35fbf6b 2421 }
034c6ed7 2422
d35fbf6b 2423 if (!strv_isempty(context->runtime_directory) && params->runtime_prefix) {
07689d5d
LP
2424 r = setup_runtime_directory(context, params, uid, gid);
2425 if (r < 0) {
2426 *exit_status = EXIT_RUNTIME_DIRECTORY;
2427 return r;
d35fbf6b
DM
2428 }
2429 }
94f04347 2430
7bce046b 2431 r = build_environment(
fd63e712 2432 unit,
7bce046b
LP
2433 context,
2434 params,
2435 n_fds,
2436 home,
2437 username,
2438 shell,
2439 journal_stream_dev,
2440 journal_stream_ino,
2441 &our_env);
2065ca69
JW
2442 if (r < 0) {
2443 *exit_status = EXIT_MEMORY;
2444 return r;
2445 }
2446
2447 r = build_pass_environment(context, &pass_env);
2448 if (r < 0) {
2449 *exit_status = EXIT_MEMORY;
2450 return r;
2451 }
2452
2453 accum_env = strv_env_merge(5,
2454 params->environment,
2455 our_env,
2456 pass_env,
2457 context->environment,
2458 files_env,
2459 NULL);
2460 if (!accum_env) {
2461 *exit_status = EXIT_MEMORY;
2462 return -ENOMEM;
2463 }
1280503b 2464 accum_env = strv_env_clean(accum_env);
2065ca69 2465
096424d1 2466 (void) umask(context->umask);
b213e1c1 2467
c39f1ce2 2468 if ((params->flags & EXEC_APPLY_PERMISSIONS) && !command->privileged) {
cefc33ae
LP
2469 r = setup_smack(context, command);
2470 if (r < 0) {
2471 *exit_status = EXIT_SMACK_PROCESS_LABEL;
2472 return r;
6bf6e43e 2473 }
6bf6e43e 2474
b213e1c1 2475 if (context->pam_name && username) {
2d6fce8d 2476 r = setup_pam(context->pam_name, username, uid, gid, context->tty_path, &accum_env, fds, n_fds);
b213e1c1
SW
2477 if (r < 0) {
2478 *exit_status = EXIT_PAM;
2479 return r;
2480 }
d35fbf6b 2481 }
b213e1c1 2482 }
ac45f971 2483
d35fbf6b 2484 if (context->private_network && runtime && runtime->netns_storage_socket[0] >= 0) {
ff0af2a1
LP
2485 r = setup_netns(runtime->netns_storage_socket);
2486 if (r < 0) {
2487 *exit_status = EXIT_NETWORK;
2488 return r;
d35fbf6b
DM
2489 }
2490 }
169c1bda 2491
ee818b89 2492 needs_mount_namespace = exec_needs_mount_namespace(context, params, runtime);
ee818b89 2493 if (needs_mount_namespace) {
3fbe8dbe 2494 _cleanup_free_ char **rw = NULL;
d35fbf6b
DM
2495 char *tmp = NULL, *var = NULL;
2496
2497 /* The runtime struct only contains the parent
2498 * of the private /tmp, which is
2499 * non-accessible to world users. Inside of it
2500 * there's a /tmp that is sticky, and that's
2501 * the one we want to use here. */
2502
2503 if (context->private_tmp && runtime) {
2504 if (runtime->tmp_dir)
63c372cb 2505 tmp = strjoina(runtime->tmp_dir, "/tmp");
d35fbf6b 2506 if (runtime->var_tmp_dir)
63c372cb 2507 var = strjoina(runtime->var_tmp_dir, "/tmp");
d35fbf6b 2508 }
d8b4e2e9 2509
3fbe8dbe
LP
2510 r = compile_read_write_paths(context, params, &rw);
2511 if (r < 0) {
2512 *exit_status = EXIT_NAMESPACE;
2513 return r;
2514 }
2515
ff0af2a1 2516 r = setup_namespace(
c39f1ce2 2517 (params->flags & EXEC_APPLY_CHROOT) ? context->root_directory : NULL,
3fbe8dbe 2518 rw,
2a624c36
AP
2519 context->read_only_paths,
2520 context->inaccessible_paths,
d35fbf6b
DM
2521 tmp,
2522 var,
2523 context->private_devices,
59eeb84b
LP
2524 context->protect_kernel_tunables,
2525 context->protect_control_groups,
d35fbf6b
DM
2526 context->protect_home,
2527 context->protect_system,
2528 context->mount_flags);
0015ebf3 2529
ff0af2a1
LP
2530 /* If we couldn't set up the namespace this is
2531 * probably due to a missing capability. In this case,
2532 * silently proceeed. */
2533 if (r == -EPERM || r == -EACCES) {
2534 log_open();
f2341e0a 2535 log_unit_debug_errno(unit, r, "Failed to set up namespace, assuming containerized execution, ignoring: %m");
ff0af2a1
LP
2536 log_close();
2537 } else if (r < 0) {
2538 *exit_status = EXIT_NAMESPACE;
2539 return r;
81a2b7ce 2540 }
d35fbf6b 2541 }
81a2b7ce 2542
096424d1
LP
2543 if ((params->flags & EXEC_APPLY_PERMISSIONS) && !command->privileged) {
2544 r = enforce_groups(context, username, gid);
2545 if (r < 0) {
2546 *exit_status = EXIT_GROUP;
2547 return r;
2548 }
2549 }
2550
5f5d8eab
LP
2551 if (context->working_directory_home)
2552 wd = home;
2553 else if (context->working_directory)
2554 wd = context->working_directory;
2555 else
2556 wd = "/";
2557
c39f1ce2 2558 if (params->flags & EXEC_APPLY_CHROOT) {
ee818b89 2559 if (!needs_mount_namespace && context->root_directory)
d35fbf6b 2560 if (chroot(context->root_directory) < 0) {
ff0af2a1 2561 *exit_status = EXIT_CHROOT;
d35fbf6b 2562 return -errno;
8aa75193
LP
2563 }
2564
5f5d8eab 2565 if (chdir(wd) < 0 &&
4c08c824 2566 !context->working_directory_missing_ok) {
ff0af2a1 2567 *exit_status = EXIT_CHDIR;
d35fbf6b
DM
2568 return -errno;
2569 }
2570 } else {
5f5d8eab 2571 const char *d;
8aa75193 2572
5f5d8eab 2573 d = strjoina(strempty(context->root_directory), "/", strempty(wd));
cf1d0302
LP
2574 if (chdir(d) < 0 &&
2575 !context->working_directory_missing_ok) {
ff0af2a1 2576 *exit_status = EXIT_CHDIR;
d35fbf6b
DM
2577 return -errno;
2578 }
2579 }
e66cf1a3 2580
9008e1ac 2581#ifdef HAVE_SELINUX
c39f1ce2
LP
2582 if ((params->flags & EXEC_APPLY_PERMISSIONS) &&
2583 mac_selinux_use() &&
2584 params->selinux_context_net &&
2585 socket_fd >= 0 &&
2586 !command->privileged) {
2587
ff0af2a1
LP
2588 r = mac_selinux_get_child_mls_label(socket_fd, command->path, context->selinux_context, &mac_selinux_context_net);
2589 if (r < 0) {
2590 *exit_status = EXIT_SELINUX_CONTEXT;
2591 return r;
9008e1ac
MS
2592 }
2593 }
2594#endif
2595
d87a2ef7 2596 if ((params->flags & EXEC_APPLY_PERMISSIONS) && context->private_users) {
d251207d
LP
2597 r = setup_private_users(uid, gid);
2598 if (r < 0) {
2599 *exit_status = EXIT_USER;
2600 return r;
2601 }
2602 }
2603
d35fbf6b
DM
2604 /* We repeat the fd closing here, to make sure that
2605 * nothing is leaked from the PAM modules. Note that
2606 * we are more aggressive this time since socket_fd
e44da745
DM
2607 * and the netns fds we don't need anymore. The custom
2608 * endpoint fd was needed to upload the policy and can
2609 * now be closed as well. */
ff0af2a1
LP
2610 r = close_all_fds(fds, n_fds);
2611 if (r >= 0)
2612 r = shift_fds(fds, n_fds);
2613 if (r >= 0)
2614 r = flags_fds(fds, n_fds, context->non_blocking);
2615 if (r < 0) {
2616 *exit_status = EXIT_FDS;
2617 return r;
d35fbf6b 2618 }
e66cf1a3 2619
c39f1ce2 2620 if ((params->flags & EXEC_APPLY_PERMISSIONS) && !command->privileged) {
e66cf1a3 2621
755d4b67
IP
2622 int secure_bits = context->secure_bits;
2623
d35fbf6b 2624 for (i = 0; i < _RLIMIT_MAX; i++) {
03857c43 2625
d35fbf6b
DM
2626 if (!context->rlimit[i])
2627 continue;
2628
03857c43
LP
2629 r = setrlimit_closest(i, context->rlimit[i]);
2630 if (r < 0) {
ff0af2a1 2631 *exit_status = EXIT_LIMITS;
03857c43 2632 return r;
e66cf1a3
LP
2633 }
2634 }
2635
f4170c67
LP
2636 /* Set the RTPRIO resource limit to 0, but only if nothing else was explicitly requested. */
2637 if (context->restrict_realtime && !context->rlimit[RLIMIT_RTPRIO]) {
2638 if (setrlimit(RLIMIT_RTPRIO, &RLIMIT_MAKE_CONST(0)) < 0) {
2639 *exit_status = EXIT_LIMITS;
2640 return -errno;
2641 }
2642 }
2643
a103496c
IP
2644 if (!cap_test_all(context->capability_bounding_set)) {
2645 r = capability_bounding_set_drop(context->capability_bounding_set, false);
ff0af2a1
LP
2646 if (r < 0) {
2647 *exit_status = EXIT_CAPABILITIES;
2648 return r;
3b8bddde 2649 }
4c2630eb 2650 }
3b8bddde 2651
755d4b67
IP
2652 /* This is done before enforce_user, but ambient set
2653 * does not survive over setresuid() if keep_caps is not set. */
2654 if (context->capability_ambient_set != 0) {
2655 r = capability_ambient_set_apply(context->capability_ambient_set, true);
2656 if (r < 0) {
2657 *exit_status = EXIT_CAPABILITIES;
2658 return r;
2659 }
755d4b67
IP
2660 }
2661
d35fbf6b 2662 if (context->user) {
ff0af2a1
LP
2663 r = enforce_user(context, uid);
2664 if (r < 0) {
2665 *exit_status = EXIT_USER;
2666 return r;
5b6319dc 2667 }
755d4b67
IP
2668 if (context->capability_ambient_set != 0) {
2669
2670 /* Fix the ambient capabilities after user change. */
2671 r = capability_ambient_set_apply(context->capability_ambient_set, false);
2672 if (r < 0) {
2673 *exit_status = EXIT_CAPABILITIES;
2674 return r;
2675 }
2676
2677 /* If we were asked to change user and ambient capabilities
2678 * were requested, we had to add keep-caps to the securebits
2679 * so that we would maintain the inherited capability set
2680 * through the setresuid(). Make sure that the bit is added
2681 * also to the context secure_bits so that we don't try to
2682 * drop the bit away next. */
2683
7f508f2c 2684 secure_bits |= 1<<SECURE_KEEP_CAPS;
755d4b67 2685 }
5b6319dc 2686 }
d35fbf6b
DM
2687
2688 /* PR_GET_SECUREBITS is not privileged, while
2689 * PR_SET_SECUREBITS is. So to suppress
2690 * potential EPERMs we'll try not to call
2691 * PR_SET_SECUREBITS unless necessary. */
755d4b67
IP
2692 if (prctl(PR_GET_SECUREBITS) != secure_bits)
2693 if (prctl(PR_SET_SECUREBITS, secure_bits) < 0) {
ff0af2a1 2694 *exit_status = EXIT_SECUREBITS;
d35fbf6b 2695 return -errno;
ff01d048 2696 }
5b6319dc 2697
59eeb84b 2698 if (context_has_no_new_privileges(context))
d35fbf6b 2699 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
ff0af2a1 2700 *exit_status = EXIT_NO_NEW_PRIVILEGES;
d35fbf6b
DM
2701 return -errno;
2702 }
2703
2704#ifdef HAVE_SECCOMP
59eeb84b 2705 if (context_has_address_families(context)) {
83f12b27 2706 r = apply_address_families(unit, context);
ff0af2a1
LP
2707 if (r < 0) {
2708 *exit_status = EXIT_ADDRESS_FAMILIES;
2709 return r;
4c2630eb
MS
2710 }
2711 }
04aa0cb9 2712
f3e43635 2713 if (context->memory_deny_write_execute) {
83f12b27 2714 r = apply_memory_deny_write_execute(unit, context);
f3e43635
TM
2715 if (r < 0) {
2716 *exit_status = EXIT_SECCOMP;
2717 return r;
2718 }
2719 }
f4170c67
LP
2720
2721 if (context->restrict_realtime) {
83f12b27 2722 r = apply_restrict_realtime(unit, context);
f4170c67
LP
2723 if (r < 0) {
2724 *exit_status = EXIT_SECCOMP;
2725 return r;
2726 }
2727 }
2728
59eeb84b
LP
2729 if (context->protect_kernel_tunables) {
2730 r = apply_protect_sysctl(unit, context);
2731 if (r < 0) {
2732 *exit_status = EXIT_SECCOMP;
2733 return r;
502d704e
DH
2734 }
2735 }
2736
2737 if (context->protect_kernel_modules) {
2738 r = apply_protect_kernel_modules(unit, context);
2739 if (r < 0) {
2740 *exit_status = EXIT_SECCOMP;
2741 return r;
59eeb84b
LP
2742 }
2743 }
2744
ba128bb8
LP
2745 if (context->private_devices) {
2746 r = apply_private_devices(unit, context);
2747 if (r < 0) {
2748 *exit_status = EXIT_SECCOMP;
2749 return r;
2750 }
2751 }
2752
59eeb84b 2753 if (context_has_syscall_filters(context)) {
83f12b27 2754 r = apply_seccomp(unit, context);
ff0af2a1
LP
2755 if (r < 0) {
2756 *exit_status = EXIT_SECCOMP;
2757 return r;
81a2b7ce 2758 }
d35fbf6b
DM
2759 }
2760#endif
81a2b7ce 2761
d35fbf6b 2762#ifdef HAVE_SELINUX
6baa7db0 2763 if (mac_selinux_use()) {
9008e1ac 2764 char *exec_context = mac_selinux_context_net ?: context->selinux_context;
16115b0a 2765
9008e1ac 2766 if (exec_context) {
ff0af2a1
LP
2767 r = setexeccon(exec_context);
2768 if (r < 0) {
2769 *exit_status = EXIT_SELINUX_CONTEXT;
2770 return r;
16115b0a 2771 }
81a2b7ce 2772 }
81a2b7ce 2773 }
d35fbf6b 2774#endif
81a2b7ce 2775
d35fbf6b 2776#ifdef HAVE_APPARMOR
6baa7db0 2777 if (context->apparmor_profile && mac_apparmor_use()) {
ff0af2a1
LP
2778 r = aa_change_onexec(context->apparmor_profile);
2779 if (r < 0 && !context->apparmor_profile_ignore) {
2780 *exit_status = EXIT_APPARMOR_PROFILE;
5482192e 2781 return -errno;
d35fbf6b 2782 }
034c6ed7 2783 }
d35fbf6b
DM
2784#endif
2785 }
034c6ed7 2786
2065ca69 2787 final_argv = replace_env_argv(argv, accum_env);
d35fbf6b 2788 if (!final_argv) {
ff0af2a1 2789 *exit_status = EXIT_MEMORY;
d35fbf6b
DM
2790 return -ENOMEM;
2791 }
034c6ed7 2792
553d2243 2793 if (_unlikely_(log_get_max_level() >= LOG_DEBUG)) {
d35fbf6b 2794 _cleanup_free_ char *line;
81a2b7ce 2795
d35fbf6b
DM
2796 line = exec_command_line(final_argv);
2797 if (line) {
2798 log_open();
f2341e0a
LP
2799 log_struct(LOG_DEBUG,
2800 LOG_UNIT_ID(unit),
2801 "EXECUTABLE=%s", command->path,
2802 LOG_UNIT_MESSAGE(unit, "Executing: %s", line),
2803 NULL);
d35fbf6b
DM
2804 log_close();
2805 }
2806 }
dd305ec9 2807
2065ca69 2808 execve(command->path, final_argv, accum_env);
ff0af2a1 2809 *exit_status = EXIT_EXEC;
d35fbf6b
DM
2810 return -errno;
2811}
81a2b7ce 2812
f2341e0a
LP
2813int exec_spawn(Unit *unit,
2814 ExecCommand *command,
d35fbf6b
DM
2815 const ExecContext *context,
2816 const ExecParameters *params,
2817 ExecRuntime *runtime,
29206d46 2818 DynamicCreds *dcreds,
d35fbf6b 2819 pid_t *ret) {
8351ceae 2820
d35fbf6b
DM
2821 _cleanup_strv_free_ char **files_env = NULL;
2822 int *fds = NULL; unsigned n_fds = 0;
ff0af2a1
LP
2823 _cleanup_free_ char *line = NULL;
2824 int socket_fd, r;
2825 char **argv;
d35fbf6b 2826 pid_t pid;
8351ceae 2827
f2341e0a 2828 assert(unit);
d35fbf6b
DM
2829 assert(command);
2830 assert(context);
2831 assert(ret);
2832 assert(params);
2833 assert(params->fds || params->n_fds <= 0);
4298d0b5 2834
d35fbf6b
DM
2835 if (context->std_input == EXEC_INPUT_SOCKET ||
2836 context->std_output == EXEC_OUTPUT_SOCKET ||
2837 context->std_error == EXEC_OUTPUT_SOCKET) {
17df7223 2838
ff0af2a1 2839 if (params->n_fds != 1) {
f2341e0a 2840 log_unit_error(unit, "Got more than one socket.");
d35fbf6b 2841 return -EINVAL;
ff0af2a1 2842 }
eef65bf3 2843
d35fbf6b
DM
2844 socket_fd = params->fds[0];
2845 } else {
2846 socket_fd = -1;
2847 fds = params->fds;
2848 n_fds = params->n_fds;
2849 }
94f04347 2850
f2341e0a 2851 r = exec_context_load_environment(unit, context, &files_env);
ff0af2a1 2852 if (r < 0)
f2341e0a 2853 return log_unit_error_errno(unit, r, "Failed to load environment files: %m");
034c6ed7 2854
d35fbf6b 2855 argv = params->argv ?: command->argv;
d35fbf6b
DM
2856 line = exec_command_line(argv);
2857 if (!line)
2858 return log_oom();
fab56fc5 2859
f2341e0a
LP
2860 log_struct(LOG_DEBUG,
2861 LOG_UNIT_ID(unit),
2862 LOG_UNIT_MESSAGE(unit, "About to execute: %s", line),
2863 "EXECUTABLE=%s", command->path,
2864 NULL);
d35fbf6b
DM
2865 pid = fork();
2866 if (pid < 0)
74129a12 2867 return log_unit_error_errno(unit, errno, "Failed to fork: %m");
d35fbf6b
DM
2868
2869 if (pid == 0) {
ff0af2a1
LP
2870 int exit_status;
2871
f2341e0a
LP
2872 r = exec_child(unit,
2873 command,
ff0af2a1
LP
2874 context,
2875 params,
2876 runtime,
29206d46 2877 dcreds,
ff0af2a1
LP
2878 argv,
2879 socket_fd,
2880 fds, n_fds,
2881 files_env,
00d9ef85 2882 unit->manager->user_lookup_fds[1],
ff0af2a1
LP
2883 &exit_status);
2884 if (r < 0) {
4c2630eb 2885 log_open();
f2341e0a
LP
2886 log_struct_errno(LOG_ERR, r,
2887 LOG_MESSAGE_ID(SD_MESSAGE_SPAWN_FAILED),
2888 LOG_UNIT_ID(unit),
2889 LOG_UNIT_MESSAGE(unit, "Failed at step %s spawning %s: %m",
2890 exit_status_to_string(exit_status, EXIT_STATUS_SYSTEMD),
2891 command->path),
2892 "EXECUTABLE=%s", command->path,
2893 NULL);
4c2630eb
MS
2894 }
2895
ff0af2a1 2896 _exit(exit_status);
034c6ed7
LP
2897 }
2898
f2341e0a 2899 log_unit_debug(unit, "Forked %s as "PID_FMT, command->path, pid);
23635a85 2900
80876c20
LP
2901 /* We add the new process to the cgroup both in the child (so
2902 * that we can be sure that no user code is ever executed
2903 * outside of the cgroup) and in the parent (so that we can be
2904 * sure that when we kill the cgroup the process will be
2905 * killed too). */
d35fbf6b 2906 if (params->cgroup_path)
dd305ec9 2907 (void) cg_attach(SYSTEMD_CGROUP_CONTROLLER, params->cgroup_path, pid);
2da3263a 2908
b58b4116 2909 exec_status_start(&command->exec_status, pid);
9fb86720 2910
034c6ed7 2911 *ret = pid;
5cb5a6ff
LP
2912 return 0;
2913}
2914
034c6ed7
LP
2915void exec_context_init(ExecContext *c) {
2916 assert(c);
2917
4c12626c 2918 c->umask = 0022;
9eba9da4 2919 c->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 0);
94f04347 2920 c->cpu_sched_policy = SCHED_OTHER;
071830ff 2921 c->syslog_priority = LOG_DAEMON|LOG_INFO;
74922904 2922 c->syslog_level_prefix = true;
353e12c2 2923 c->ignore_sigpipe = true;
3a43da28 2924 c->timer_slack_nsec = NSEC_INFINITY;
050f7277 2925 c->personality = PERSONALITY_INVALID;
e66cf1a3 2926 c->runtime_directory_mode = 0755;
a103496c 2927 c->capability_bounding_set = CAP_ALL;
034c6ed7
LP
2928}
2929
613b411c 2930void exec_context_done(ExecContext *c) {
5cb5a6ff
LP
2931 unsigned l;
2932
2933 assert(c);
2934
6796073e
LP
2935 c->environment = strv_free(c->environment);
2936 c->environment_files = strv_free(c->environment_files);
b4c14404 2937 c->pass_environment = strv_free(c->pass_environment);
8c7be95e 2938
1f6b4113 2939 for (l = 0; l < ELEMENTSOF(c->rlimit); l++)
a1e58e8e 2940 c->rlimit[l] = mfree(c->rlimit[l]);
034c6ed7 2941
a1e58e8e
LP
2942 c->working_directory = mfree(c->working_directory);
2943 c->root_directory = mfree(c->root_directory);
2944 c->tty_path = mfree(c->tty_path);
2945 c->syslog_identifier = mfree(c->syslog_identifier);
2946 c->user = mfree(c->user);
2947 c->group = mfree(c->group);
034c6ed7 2948
6796073e 2949 c->supplementary_groups = strv_free(c->supplementary_groups);
94f04347 2950
a1e58e8e 2951 c->pam_name = mfree(c->pam_name);
5b6319dc 2952
2a624c36
AP
2953 c->read_only_paths = strv_free(c->read_only_paths);
2954 c->read_write_paths = strv_free(c->read_write_paths);
2955 c->inaccessible_paths = strv_free(c->inaccessible_paths);
82c121a4
LP
2956
2957 if (c->cpuset)
2958 CPU_FREE(c->cpuset);
86a3475b 2959
a1e58e8e
LP
2960 c->utmp_id = mfree(c->utmp_id);
2961 c->selinux_context = mfree(c->selinux_context);
2962 c->apparmor_profile = mfree(c->apparmor_profile);
eef65bf3 2963
525d3cc7
LP
2964 c->syscall_filter = set_free(c->syscall_filter);
2965 c->syscall_archs = set_free(c->syscall_archs);
2966 c->address_families = set_free(c->address_families);
e66cf1a3 2967
6796073e 2968 c->runtime_directory = strv_free(c->runtime_directory);
e66cf1a3
LP
2969}
2970
2971int exec_context_destroy_runtime_directory(ExecContext *c, const char *runtime_prefix) {
2972 char **i;
2973
2974 assert(c);
2975
2976 if (!runtime_prefix)
2977 return 0;
2978
2979 STRV_FOREACH(i, c->runtime_directory) {
2980 _cleanup_free_ char *p;
2981
2982 p = strjoin(runtime_prefix, "/", *i, NULL);
2983 if (!p)
2984 return -ENOMEM;
2985
2986 /* We execute this synchronously, since we need to be
2987 * sure this is gone when we start the service
2988 * next. */
c6878637 2989 (void) rm_rf(p, REMOVE_ROOT);
e66cf1a3
LP
2990 }
2991
2992 return 0;
5cb5a6ff
LP
2993}
2994
43d0fcbd
LP
2995void exec_command_done(ExecCommand *c) {
2996 assert(c);
2997
a1e58e8e 2998 c->path = mfree(c->path);
43d0fcbd 2999
6796073e 3000 c->argv = strv_free(c->argv);
43d0fcbd
LP
3001}
3002
3003void exec_command_done_array(ExecCommand *c, unsigned n) {
3004 unsigned i;
3005
3006 for (i = 0; i < n; i++)
3007 exec_command_done(c+i);
3008}
3009
f1acf85a 3010ExecCommand* exec_command_free_list(ExecCommand *c) {
5cb5a6ff
LP
3011 ExecCommand *i;
3012
3013 while ((i = c)) {
71fda00f 3014 LIST_REMOVE(command, c, i);
43d0fcbd 3015 exec_command_done(i);
5cb5a6ff
LP
3016 free(i);
3017 }
f1acf85a
ZJS
3018
3019 return NULL;
5cb5a6ff
LP
3020}
3021
034c6ed7
LP
3022void exec_command_free_array(ExecCommand **c, unsigned n) {
3023 unsigned i;
3024
f1acf85a
ZJS
3025 for (i = 0; i < n; i++)
3026 c[i] = exec_command_free_list(c[i]);
034c6ed7
LP
3027}
3028
039f0e70 3029typedef struct InvalidEnvInfo {
f2341e0a 3030 Unit *unit;
039f0e70
LP
3031 const char *path;
3032} InvalidEnvInfo;
3033
3034static void invalid_env(const char *p, void *userdata) {
3035 InvalidEnvInfo *info = userdata;
3036
f2341e0a 3037 log_unit_error(info->unit, "Ignoring invalid environment assignment '%s': %s", p, info->path);
039f0e70
LP
3038}
3039
f2341e0a 3040int exec_context_load_environment(Unit *unit, const ExecContext *c, char ***l) {
8c7be95e
LP
3041 char **i, **r = NULL;
3042
3043 assert(c);
3044 assert(l);
3045
3046 STRV_FOREACH(i, c->environment_files) {
3047 char *fn;
3048 int k;
3049 bool ignore = false;
3050 char **p;
7fd1b19b 3051 _cleanup_globfree_ glob_t pglob = {};
2bef10ab 3052 int count, n;
8c7be95e
LP
3053
3054 fn = *i;
3055
3056 if (fn[0] == '-') {
3057 ignore = true;
313cefa1 3058 fn++;
8c7be95e
LP
3059 }
3060
3061 if (!path_is_absolute(fn)) {
8c7be95e
LP
3062 if (ignore)
3063 continue;
3064
3065 strv_free(r);
3066 return -EINVAL;
3067 }
3068
2bef10ab 3069 /* Filename supports globbing, take all matching files */
2bef10ab
PL
3070 errno = 0;
3071 if (glob(fn, 0, NULL, &pglob) != 0) {
2bef10ab
PL
3072 if (ignore)
3073 continue;
8c7be95e 3074
2bef10ab 3075 strv_free(r);
f5e5c28f 3076 return errno > 0 ? -errno : -EINVAL;
2bef10ab
PL
3077 }
3078 count = pglob.gl_pathc;
3079 if (count == 0) {
8c7be95e
LP
3080 if (ignore)
3081 continue;
3082
3083 strv_free(r);
2bef10ab 3084 return -EINVAL;
8c7be95e 3085 }
2bef10ab 3086 for (n = 0; n < count; n++) {
717603e3 3087 k = load_env_file(NULL, pglob.gl_pathv[n], NULL, &p);
2bef10ab
PL
3088 if (k < 0) {
3089 if (ignore)
3090 continue;
8c7be95e 3091
2bef10ab 3092 strv_free(r);
2bef10ab 3093 return k;
e9c1ea9d 3094 }
ebc05a09 3095 /* Log invalid environment variables with filename */
039f0e70
LP
3096 if (p) {
3097 InvalidEnvInfo info = {
f2341e0a 3098 .unit = unit,
039f0e70
LP
3099 .path = pglob.gl_pathv[n]
3100 };
3101
3102 p = strv_env_clean_with_callback(p, invalid_env, &info);
3103 }
8c7be95e 3104
2bef10ab
PL
3105 if (r == NULL)
3106 r = p;
3107 else {
3108 char **m;
8c7be95e 3109
2bef10ab
PL
3110 m = strv_env_merge(2, r, p);
3111 strv_free(r);
3112 strv_free(p);
c84a9488 3113 if (!m)
2bef10ab 3114 return -ENOMEM;
2bef10ab
PL
3115
3116 r = m;
3117 }
8c7be95e
LP
3118 }
3119 }
3120
3121 *l = r;
3122
3123 return 0;
3124}
3125
6ac8fdc9 3126static bool tty_may_match_dev_console(const char *tty) {
e1d75803 3127 _cleanup_free_ char *active = NULL;
7d6884b6 3128 char *console;
6ac8fdc9 3129
1e22b5cd
LP
3130 if (!tty)
3131 return true;
3132
6ac8fdc9
MS
3133 if (startswith(tty, "/dev/"))
3134 tty += 5;
3135
3136 /* trivial identity? */
3137 if (streq(tty, "console"))
3138 return true;
3139
3140 console = resolve_dev_console(&active);
3141 /* if we could not resolve, assume it may */
3142 if (!console)
3143 return true;
3144
3145 /* "tty0" means the active VC, so it may be the same sometimes */
e1d75803 3146 return streq(console, tty) || (streq(console, "tty0") && tty_is_vc(tty));
6ac8fdc9
MS
3147}
3148
3149bool exec_context_may_touch_console(ExecContext *ec) {
1e22b5cd
LP
3150
3151 return (ec->tty_reset ||
3152 ec->tty_vhangup ||
3153 ec->tty_vt_disallocate ||
6ac8fdc9
MS
3154 is_terminal_input(ec->std_input) ||
3155 is_terminal_output(ec->std_output) ||
3156 is_terminal_output(ec->std_error)) &&
1e22b5cd 3157 tty_may_match_dev_console(exec_context_tty_path(ec));
6ac8fdc9
MS
3158}
3159
15ae422b
LP
3160static void strv_fprintf(FILE *f, char **l) {
3161 char **g;
3162
3163 assert(f);
3164
3165 STRV_FOREACH(g, l)
3166 fprintf(f, " %s", *g);
3167}
3168
5cb5a6ff 3169void exec_context_dump(ExecContext *c, FILE* f, const char *prefix) {
c2bbd90b 3170 char **e, **d;
94f04347 3171 unsigned i;
9eba9da4 3172
5cb5a6ff
LP
3173 assert(c);
3174 assert(f);
3175
4ad49000 3176 prefix = strempty(prefix);
5cb5a6ff
LP
3177
3178 fprintf(f,
94f04347
LP
3179 "%sUMask: %04o\n"
3180 "%sWorkingDirectory: %s\n"
451a074f 3181 "%sRootDirectory: %s\n"
15ae422b 3182 "%sNonBlocking: %s\n"
64747e2d 3183 "%sPrivateTmp: %s\n"
7f112f50 3184 "%sPrivateDevices: %s\n"
59eeb84b
LP
3185 "%sProtectKernelTunables: %s\n"
3186 "%sProtectControlGroups: %s\n"
d251207d
LP
3187 "%sPrivateNetwork: %s\n"
3188 "%sPrivateUsers: %s\n"
1b8689f9
LP
3189 "%sProtectHome: %s\n"
3190 "%sProtectSystem: %s\n"
f3e43635 3191 "%sIgnoreSIGPIPE: %s\n"
f4170c67
LP
3192 "%sMemoryDenyWriteExecute: %s\n"
3193 "%sRestrictRealtime: %s\n",
5cb5a6ff 3194 prefix, c->umask,
9eba9da4 3195 prefix, c->working_directory ? c->working_directory : "/",
451a074f 3196 prefix, c->root_directory ? c->root_directory : "/",
15ae422b 3197 prefix, yes_no(c->non_blocking),
64747e2d 3198 prefix, yes_no(c->private_tmp),
7f112f50 3199 prefix, yes_no(c->private_devices),
59eeb84b
LP
3200 prefix, yes_no(c->protect_kernel_tunables),
3201 prefix, yes_no(c->protect_control_groups),
d251207d
LP
3202 prefix, yes_no(c->private_network),
3203 prefix, yes_no(c->private_users),
1b8689f9
LP
3204 prefix, protect_home_to_string(c->protect_home),
3205 prefix, protect_system_to_string(c->protect_system),
f3e43635 3206 prefix, yes_no(c->ignore_sigpipe),
f4170c67
LP
3207 prefix, yes_no(c->memory_deny_write_execute),
3208 prefix, yes_no(c->restrict_realtime));
fb33a393 3209
8c7be95e
LP
3210 STRV_FOREACH(e, c->environment)
3211 fprintf(f, "%sEnvironment: %s\n", prefix, *e);
3212
3213 STRV_FOREACH(e, c->environment_files)
3214 fprintf(f, "%sEnvironmentFile: %s\n", prefix, *e);
94f04347 3215
b4c14404
FB
3216 STRV_FOREACH(e, c->pass_environment)
3217 fprintf(f, "%sPassEnvironment: %s\n", prefix, *e);
3218
c2bbd90b
EV
3219 fprintf(f, "%sRuntimeDirectoryMode: %04o\n", prefix, c->runtime_directory_mode);
3220
3221 STRV_FOREACH(d, c->runtime_directory)
3222 fprintf(f, "%sRuntimeDirectory: %s\n", prefix, *d);
3223
fb33a393
LP
3224 if (c->nice_set)
3225 fprintf(f,
3226 "%sNice: %i\n",
3227 prefix, c->nice);
3228
dd6c17b1 3229 if (c->oom_score_adjust_set)
fb33a393 3230 fprintf(f,
dd6c17b1
LP
3231 "%sOOMScoreAdjust: %i\n",
3232 prefix, c->oom_score_adjust);
9eba9da4 3233
94f04347 3234 for (i = 0; i < RLIM_NLIMITS; i++)
3c11da9d
EV
3235 if (c->rlimit[i]) {
3236 fprintf(f, "%s%s: " RLIM_FMT "\n",
3237 prefix, rlimit_to_string(i), c->rlimit[i]->rlim_max);
3238 fprintf(f, "%s%sSoft: " RLIM_FMT "\n",
3239 prefix, rlimit_to_string(i), c->rlimit[i]->rlim_cur);
3240 }
94f04347 3241
f8b69d1d 3242 if (c->ioprio_set) {
1756a011 3243 _cleanup_free_ char *class_str = NULL;
f8b69d1d 3244
1756a011 3245 ioprio_class_to_string_alloc(IOPRIO_PRIO_CLASS(c->ioprio), &class_str);
9eba9da4
LP
3246 fprintf(f,
3247 "%sIOSchedulingClass: %s\n"
3248 "%sIOPriority: %i\n",
f8b69d1d 3249 prefix, strna(class_str),
9eba9da4 3250 prefix, (int) IOPRIO_PRIO_DATA(c->ioprio));
f8b69d1d 3251 }
94f04347 3252
f8b69d1d 3253 if (c->cpu_sched_set) {
1756a011 3254 _cleanup_free_ char *policy_str = NULL;
f8b69d1d 3255
1756a011 3256 sched_policy_to_string_alloc(c->cpu_sched_policy, &policy_str);
94f04347
LP
3257 fprintf(f,
3258 "%sCPUSchedulingPolicy: %s\n"
38b48754
LP
3259 "%sCPUSchedulingPriority: %i\n"
3260 "%sCPUSchedulingResetOnFork: %s\n",
f8b69d1d 3261 prefix, strna(policy_str),
38b48754
LP
3262 prefix, c->cpu_sched_priority,
3263 prefix, yes_no(c->cpu_sched_reset_on_fork));
b929bf04 3264 }
94f04347 3265
82c121a4 3266 if (c->cpuset) {
94f04347 3267 fprintf(f, "%sCPUAffinity:", prefix);
82c121a4
LP
3268 for (i = 0; i < c->cpuset_ncpus; i++)
3269 if (CPU_ISSET_S(i, CPU_ALLOC_SIZE(c->cpuset_ncpus), c->cpuset))
43a99a7a 3270 fprintf(f, " %u", i);
94f04347
LP
3271 fputs("\n", f);
3272 }
3273
3a43da28 3274 if (c->timer_slack_nsec != NSEC_INFINITY)
ccd06097 3275 fprintf(f, "%sTimerSlackNSec: "NSEC_FMT "\n", prefix, c->timer_slack_nsec);
94f04347
LP
3276
3277 fprintf(f,
80876c20
LP
3278 "%sStandardInput: %s\n"
3279 "%sStandardOutput: %s\n"
3280 "%sStandardError: %s\n",
3281 prefix, exec_input_to_string(c->std_input),
3282 prefix, exec_output_to_string(c->std_output),
3283 prefix, exec_output_to_string(c->std_error));
3284
3285 if (c->tty_path)
3286 fprintf(f,
6ea832a2
LP
3287 "%sTTYPath: %s\n"
3288 "%sTTYReset: %s\n"
3289 "%sTTYVHangup: %s\n"
3290 "%sTTYVTDisallocate: %s\n",
3291 prefix, c->tty_path,
3292 prefix, yes_no(c->tty_reset),
3293 prefix, yes_no(c->tty_vhangup),
3294 prefix, yes_no(c->tty_vt_disallocate));
94f04347 3295
5ce70e5b
ZJS
3296 if (c->std_output == EXEC_OUTPUT_SYSLOG ||
3297 c->std_output == EXEC_OUTPUT_KMSG ||
3298 c->std_output == EXEC_OUTPUT_JOURNAL ||
3299 c->std_output == EXEC_OUTPUT_SYSLOG_AND_CONSOLE ||
3300 c->std_output == EXEC_OUTPUT_KMSG_AND_CONSOLE ||
3301 c->std_output == EXEC_OUTPUT_JOURNAL_AND_CONSOLE ||
3302 c->std_error == EXEC_OUTPUT_SYSLOG ||
3303 c->std_error == EXEC_OUTPUT_KMSG ||
3304 c->std_error == EXEC_OUTPUT_JOURNAL ||
3305 c->std_error == EXEC_OUTPUT_SYSLOG_AND_CONSOLE ||
3306 c->std_error == EXEC_OUTPUT_KMSG_AND_CONSOLE ||
3307 c->std_error == EXEC_OUTPUT_JOURNAL_AND_CONSOLE) {
f8b69d1d 3308
5ce70e5b 3309 _cleanup_free_ char *fac_str = NULL, *lvl_str = NULL;
f8b69d1d 3310
5ce70e5b
ZJS
3311 log_facility_unshifted_to_string_alloc(c->syslog_priority >> 3, &fac_str);
3312 log_level_to_string_alloc(LOG_PRI(c->syslog_priority), &lvl_str);
f8b69d1d 3313
94f04347
LP
3314 fprintf(f,
3315 "%sSyslogFacility: %s\n"
3316 "%sSyslogLevel: %s\n",
f8b69d1d
MS
3317 prefix, strna(fac_str),
3318 prefix, strna(lvl_str));
f8b69d1d 3319 }
94f04347 3320
94f04347
LP
3321 if (c->secure_bits)
3322 fprintf(f, "%sSecure Bits:%s%s%s%s%s%s\n",
3323 prefix,
cbb21cca
ZJS
3324 (c->secure_bits & 1<<SECURE_KEEP_CAPS) ? " keep-caps" : "",
3325 (c->secure_bits & 1<<SECURE_KEEP_CAPS_LOCKED) ? " keep-caps-locked" : "",
3326 (c->secure_bits & 1<<SECURE_NO_SETUID_FIXUP) ? " no-setuid-fixup" : "",
3327 (c->secure_bits & 1<<SECURE_NO_SETUID_FIXUP_LOCKED) ? " no-setuid-fixup-locked" : "",
3328 (c->secure_bits & 1<<SECURE_NOROOT) ? " noroot" : "",
3329 (c->secure_bits & 1<<SECURE_NOROOT_LOCKED) ? "noroot-locked" : "");
94f04347 3330
a103496c 3331 if (c->capability_bounding_set != CAP_ALL) {
ae556c21 3332 unsigned long l;
260abb78 3333 fprintf(f, "%sCapabilityBoundingSet:", prefix);
94f04347 3334
64685e0c 3335 for (l = 0; l <= cap_last_cap(); l++)
a103496c 3336 if (c->capability_bounding_set & (UINT64_C(1) << l))
2822da4f 3337 fprintf(f, " %s", strna(capability_to_name(l)));
94f04347
LP
3338
3339 fputs("\n", f);
755d4b67
IP
3340 }
3341
3342 if (c->capability_ambient_set != 0) {
3343 unsigned long l;
3344 fprintf(f, "%sAmbientCapabilities:", prefix);
3345
3346 for (l = 0; l <= cap_last_cap(); l++)
3347 if (c->capability_ambient_set & (UINT64_C(1) << l))
3348 fprintf(f, " %s", strna(capability_to_name(l)));
3349
3350 fputs("\n", f);
94f04347
LP
3351 }
3352
3353 if (c->user)
f2d3769a 3354 fprintf(f, "%sUser: %s\n", prefix, c->user);
94f04347 3355 if (c->group)
f2d3769a 3356 fprintf(f, "%sGroup: %s\n", prefix, c->group);
94f04347 3357
29206d46
LP
3358 fprintf(f, "%sDynamicUser: %s\n", prefix, yes_no(c->dynamic_user));
3359
15ae422b 3360 if (strv_length(c->supplementary_groups) > 0) {
94f04347 3361 fprintf(f, "%sSupplementaryGroups:", prefix);
15ae422b
LP
3362 strv_fprintf(f, c->supplementary_groups);
3363 fputs("\n", f);
3364 }
94f04347 3365
5b6319dc 3366 if (c->pam_name)
f2d3769a 3367 fprintf(f, "%sPAMName: %s\n", prefix, c->pam_name);
5b6319dc 3368
2a624c36
AP
3369 if (strv_length(c->read_write_paths) > 0) {
3370 fprintf(f, "%sReadWritePaths:", prefix);
3371 strv_fprintf(f, c->read_write_paths);
15ae422b
LP
3372 fputs("\n", f);
3373 }
3374
2a624c36
AP
3375 if (strv_length(c->read_only_paths) > 0) {
3376 fprintf(f, "%sReadOnlyPaths:", prefix);
3377 strv_fprintf(f, c->read_only_paths);
15ae422b
LP
3378 fputs("\n", f);
3379 }
94f04347 3380
2a624c36
AP
3381 if (strv_length(c->inaccessible_paths) > 0) {
3382 fprintf(f, "%sInaccessiblePaths:", prefix);
3383 strv_fprintf(f, c->inaccessible_paths);
94f04347
LP
3384 fputs("\n", f);
3385 }
2e22afe9 3386
169c1bda
LP
3387 if (c->utmp_id)
3388 fprintf(f,
3389 "%sUtmpIdentifier: %s\n",
3390 prefix, c->utmp_id);
7b52a628
MS
3391
3392 if (c->selinux_context)
3393 fprintf(f,
5f8640fb
LP
3394 "%sSELinuxContext: %s%s\n",
3395 prefix, c->selinux_context_ignore ? "-" : "", c->selinux_context);
17df7223 3396
050f7277 3397 if (c->personality != PERSONALITY_INVALID)
ac45f971
LP
3398 fprintf(f,
3399 "%sPersonality: %s\n",
3400 prefix, strna(personality_to_string(c->personality)));
3401
17df7223 3402 if (c->syscall_filter) {
351a19b1 3403#ifdef HAVE_SECCOMP
17df7223
LP
3404 Iterator j;
3405 void *id;
3406 bool first = true;
351a19b1 3407#endif
17df7223
LP
3408
3409 fprintf(f,
57183d11 3410 "%sSystemCallFilter: ",
17df7223
LP
3411 prefix);
3412
3413 if (!c->syscall_whitelist)
3414 fputc('~', f);
3415
351a19b1 3416#ifdef HAVE_SECCOMP
17df7223
LP
3417 SET_FOREACH(id, c->syscall_filter, j) {
3418 _cleanup_free_ char *name = NULL;
3419
3420 if (first)
3421 first = false;
3422 else
3423 fputc(' ', f);
3424
57183d11 3425 name = seccomp_syscall_resolve_num_arch(SCMP_ARCH_NATIVE, PTR_TO_INT(id) - 1);
17df7223
LP
3426 fputs(strna(name), f);
3427 }
351a19b1 3428#endif
17df7223
LP
3429
3430 fputc('\n', f);
3431 }
3432
57183d11
LP
3433 if (c->syscall_archs) {
3434#ifdef HAVE_SECCOMP
3435 Iterator j;
3436 void *id;
3437#endif
3438
3439 fprintf(f,
3440 "%sSystemCallArchitectures:",
3441 prefix);
3442
3443#ifdef HAVE_SECCOMP
3444 SET_FOREACH(id, c->syscall_archs, j)
3445 fprintf(f, " %s", strna(seccomp_arch_to_string(PTR_TO_UINT32(id) - 1)));
3446#endif
3447 fputc('\n', f);
3448 }
3449
b3267152 3450 if (c->syscall_errno > 0)
17df7223
LP
3451 fprintf(f,
3452 "%sSystemCallErrorNumber: %s\n",
3453 prefix, strna(errno_to_name(c->syscall_errno)));
eef65bf3
MS
3454
3455 if (c->apparmor_profile)
3456 fprintf(f,
3457 "%sAppArmorProfile: %s%s\n",
3458 prefix, c->apparmor_profile_ignore ? "-" : "", c->apparmor_profile);
5cb5a6ff
LP
3459}
3460
a931ad47
LP
3461bool exec_context_maintains_privileges(ExecContext *c) {
3462 assert(c);
3463
61233823 3464 /* Returns true if the process forked off would run under
a931ad47
LP
3465 * an unchanged UID or as root. */
3466
3467 if (!c->user)
3468 return true;
3469
3470 if (streq(c->user, "root") || streq(c->user, "0"))
3471 return true;
3472
3473 return false;
3474}
3475
b58b4116 3476void exec_status_start(ExecStatus *s, pid_t pid) {
034c6ed7 3477 assert(s);
5cb5a6ff 3478
b58b4116
LP
3479 zero(*s);
3480 s->pid = pid;
3481 dual_timestamp_get(&s->start_timestamp);
3482}
3483
6ea832a2 3484void exec_status_exit(ExecStatus *s, ExecContext *context, pid_t pid, int code, int status) {
b58b4116
LP
3485 assert(s);
3486
0b1f4ae6 3487 if (s->pid && s->pid != pid)
b58b4116
LP
3488 zero(*s);
3489
034c6ed7 3490 s->pid = pid;
63983207 3491 dual_timestamp_get(&s->exit_timestamp);
9fb86720 3492
034c6ed7
LP
3493 s->code = code;
3494 s->status = status;
169c1bda 3495
6ea832a2
LP
3496 if (context) {
3497 if (context->utmp_id)
3498 utmp_put_dead_process(context->utmp_id, pid, code, status);
3499
1e22b5cd 3500 exec_context_tty_reset(context, NULL);
6ea832a2 3501 }
9fb86720
LP
3502}
3503
3504void exec_status_dump(ExecStatus *s, FILE *f, const char *prefix) {
3505 char buf[FORMAT_TIMESTAMP_MAX];
3506
3507 assert(s);
3508 assert(f);
3509
9fb86720
LP
3510 if (s->pid <= 0)
3511 return;
3512
4c940960
LP
3513 prefix = strempty(prefix);
3514
9fb86720 3515 fprintf(f,
ccd06097
ZJS
3516 "%sPID: "PID_FMT"\n",
3517 prefix, s->pid);
9fb86720 3518
af9d16e1 3519 if (dual_timestamp_is_set(&s->start_timestamp))
9fb86720
LP
3520 fprintf(f,
3521 "%sStart Timestamp: %s\n",
63983207 3522 prefix, format_timestamp(buf, sizeof(buf), s->start_timestamp.realtime));
9fb86720 3523
af9d16e1 3524 if (dual_timestamp_is_set(&s->exit_timestamp))
9fb86720
LP
3525 fprintf(f,
3526 "%sExit Timestamp: %s\n"
3527 "%sExit Code: %s\n"
3528 "%sExit Status: %i\n",
63983207 3529 prefix, format_timestamp(buf, sizeof(buf), s->exit_timestamp.realtime),
9fb86720
LP
3530 prefix, sigchld_code_to_string(s->code),
3531 prefix, s->status);
5cb5a6ff 3532}
44d8db9e 3533
9e2f7c11 3534char *exec_command_line(char **argv) {
44d8db9e
LP
3535 size_t k;
3536 char *n, *p, **a;
3537 bool first = true;
3538
9e2f7c11 3539 assert(argv);
44d8db9e 3540
9164977d 3541 k = 1;
9e2f7c11 3542 STRV_FOREACH(a, argv)
44d8db9e
LP
3543 k += strlen(*a)+3;
3544
3545 if (!(n = new(char, k)))
3546 return NULL;
3547
3548 p = n;
9e2f7c11 3549 STRV_FOREACH(a, argv) {
44d8db9e
LP
3550
3551 if (!first)
3552 *(p++) = ' ';
3553 else
3554 first = false;
3555
3556 if (strpbrk(*a, WHITESPACE)) {
3557 *(p++) = '\'';
3558 p = stpcpy(p, *a);
3559 *(p++) = '\'';
3560 } else
3561 p = stpcpy(p, *a);
3562
3563 }
3564
9164977d
LP
3565 *p = 0;
3566
44d8db9e
LP
3567 /* FIXME: this doesn't really handle arguments that have
3568 * spaces and ticks in them */
3569
3570 return n;
3571}
3572
3573void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
e1d75803 3574 _cleanup_free_ char *cmd = NULL;
4c940960 3575 const char *prefix2;
44d8db9e
LP
3576
3577 assert(c);
3578 assert(f);
3579
4c940960 3580 prefix = strempty(prefix);
63c372cb 3581 prefix2 = strjoina(prefix, "\t");
44d8db9e 3582
9e2f7c11 3583 cmd = exec_command_line(c->argv);
44d8db9e
LP
3584 fprintf(f,
3585 "%sCommand Line: %s\n",
3586 prefix, cmd ? cmd : strerror(ENOMEM));
3587
9fb86720 3588 exec_status_dump(&c->exec_status, f, prefix2);
44d8db9e
LP
3589}
3590
3591void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
3592 assert(f);
3593
4c940960 3594 prefix = strempty(prefix);
44d8db9e
LP
3595
3596 LIST_FOREACH(command, c, c)
3597 exec_command_dump(c, f, prefix);
3598}
94f04347 3599
a6a80b4f
LP
3600void exec_command_append_list(ExecCommand **l, ExecCommand *e) {
3601 ExecCommand *end;
3602
3603 assert(l);
3604 assert(e);
3605
3606 if (*l) {
35b8ca3a 3607 /* It's kind of important, that we keep the order here */
71fda00f
LP
3608 LIST_FIND_TAIL(command, *l, end);
3609 LIST_INSERT_AFTER(command, *l, end, e);
a6a80b4f
LP
3610 } else
3611 *l = e;
3612}
3613
26fd040d
LP
3614int exec_command_set(ExecCommand *c, const char *path, ...) {
3615 va_list ap;
3616 char **l, *p;
3617
3618 assert(c);
3619 assert(path);
3620
3621 va_start(ap, path);
3622 l = strv_new_ap(path, ap);
3623 va_end(ap);
3624
3625 if (!l)
3626 return -ENOMEM;
3627
250a918d
LP
3628 p = strdup(path);
3629 if (!p) {
26fd040d
LP
3630 strv_free(l);
3631 return -ENOMEM;
3632 }
3633
3634 free(c->path);
3635 c->path = p;
3636
3637 strv_free(c->argv);
3638 c->argv = l;
3639
3640 return 0;
3641}
3642
86b23b07 3643int exec_command_append(ExecCommand *c, const char *path, ...) {
e63ff941 3644 _cleanup_strv_free_ char **l = NULL;
86b23b07 3645 va_list ap;
86b23b07
JS
3646 int r;
3647
3648 assert(c);
3649 assert(path);
3650
3651 va_start(ap, path);
3652 l = strv_new_ap(path, ap);
3653 va_end(ap);
3654
3655 if (!l)
3656 return -ENOMEM;
3657
e287086b 3658 r = strv_extend_strv(&c->argv, l, false);
e63ff941 3659 if (r < 0)
86b23b07 3660 return r;
86b23b07
JS
3661
3662 return 0;
3663}
3664
3665
613b411c
LP
3666static int exec_runtime_allocate(ExecRuntime **rt) {
3667
3668 if (*rt)
3669 return 0;
3670
3671 *rt = new0(ExecRuntime, 1);
f146f5e1 3672 if (!*rt)
613b411c
LP
3673 return -ENOMEM;
3674
3675 (*rt)->n_ref = 1;
3676 (*rt)->netns_storage_socket[0] = (*rt)->netns_storage_socket[1] = -1;
3677
3678 return 0;
3679}
3680
3681int exec_runtime_make(ExecRuntime **rt, ExecContext *c, const char *id) {
3682 int r;
3683
3684 assert(rt);
3685 assert(c);
3686 assert(id);
3687
3688 if (*rt)
3689 return 1;
3690
3691 if (!c->private_network && !c->private_tmp)
3692 return 0;
3693
3694 r = exec_runtime_allocate(rt);
3695 if (r < 0)
3696 return r;
3697
3698 if (c->private_network && (*rt)->netns_storage_socket[0] < 0) {
33df919d 3699 if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, (*rt)->netns_storage_socket) < 0)
613b411c
LP
3700 return -errno;
3701 }
3702
3703 if (c->private_tmp && !(*rt)->tmp_dir) {
3704 r = setup_tmp_dirs(id, &(*rt)->tmp_dir, &(*rt)->var_tmp_dir);
3705 if (r < 0)
3706 return r;
3707 }
3708
3709 return 1;
3710}
3711
3712ExecRuntime *exec_runtime_ref(ExecRuntime *r) {
3713 assert(r);
3714 assert(r->n_ref > 0);
3715
3716 r->n_ref++;
3717 return r;
3718}
3719
3720ExecRuntime *exec_runtime_unref(ExecRuntime *r) {
3721
3722 if (!r)
3723 return NULL;
3724
3725 assert(r->n_ref > 0);
3726
3727 r->n_ref--;
f2341e0a
LP
3728 if (r->n_ref > 0)
3729 return NULL;
3730
3731 free(r->tmp_dir);
3732 free(r->var_tmp_dir);
3733 safe_close_pair(r->netns_storage_socket);
3734 free(r);
613b411c
LP
3735
3736 return NULL;
3737}
3738
f2341e0a 3739int exec_runtime_serialize(Unit *u, ExecRuntime *rt, FILE *f, FDSet *fds) {
613b411c
LP
3740 assert(u);
3741 assert(f);
3742 assert(fds);
3743
3744 if (!rt)
3745 return 0;
3746
3747 if (rt->tmp_dir)
3748 unit_serialize_item(u, f, "tmp-dir", rt->tmp_dir);
3749
3750 if (rt->var_tmp_dir)
3751 unit_serialize_item(u, f, "var-tmp-dir", rt->var_tmp_dir);
3752
3753 if (rt->netns_storage_socket[0] >= 0) {
3754 int copy;
3755
3756 copy = fdset_put_dup(fds, rt->netns_storage_socket[0]);
3757 if (copy < 0)
3758 return copy;
3759
3760 unit_serialize_item_format(u, f, "netns-socket-0", "%i", copy);
3761 }
3762
3763 if (rt->netns_storage_socket[1] >= 0) {
3764 int copy;
3765
3766 copy = fdset_put_dup(fds, rt->netns_storage_socket[1]);
3767 if (copy < 0)
3768 return copy;
3769
3770 unit_serialize_item_format(u, f, "netns-socket-1", "%i", copy);
3771 }
3772
3773 return 0;
3774}
3775
f2341e0a 3776int exec_runtime_deserialize_item(Unit *u, ExecRuntime **rt, const char *key, const char *value, FDSet *fds) {
613b411c
LP
3777 int r;
3778
3779 assert(rt);
3780 assert(key);
3781 assert(value);
3782
3783 if (streq(key, "tmp-dir")) {
3784 char *copy;
3785
3786 r = exec_runtime_allocate(rt);
3787 if (r < 0)
f2341e0a 3788 return log_oom();
613b411c
LP
3789
3790 copy = strdup(value);
3791 if (!copy)
3792 return log_oom();
3793
3794 free((*rt)->tmp_dir);
3795 (*rt)->tmp_dir = copy;
3796
3797 } else if (streq(key, "var-tmp-dir")) {
3798 char *copy;
3799
3800 r = exec_runtime_allocate(rt);
3801 if (r < 0)
f2341e0a 3802 return log_oom();
613b411c
LP
3803
3804 copy = strdup(value);
3805 if (!copy)
3806 return log_oom();
3807
3808 free((*rt)->var_tmp_dir);
3809 (*rt)->var_tmp_dir = copy;
3810
3811 } else if (streq(key, "netns-socket-0")) {
3812 int fd;
3813
3814 r = exec_runtime_allocate(rt);
3815 if (r < 0)
f2341e0a 3816 return log_oom();
613b411c
LP
3817
3818 if (safe_atoi(value, &fd) < 0 || !fdset_contains(fds, fd))
f2341e0a 3819 log_unit_debug(u, "Failed to parse netns socket value: %s", value);
613b411c 3820 else {
03e334a1 3821 safe_close((*rt)->netns_storage_socket[0]);
613b411c
LP
3822 (*rt)->netns_storage_socket[0] = fdset_remove(fds, fd);
3823 }
3824 } else if (streq(key, "netns-socket-1")) {
3825 int fd;
3826
3827 r = exec_runtime_allocate(rt);
3828 if (r < 0)
f2341e0a 3829 return log_oom();
613b411c
LP
3830
3831 if (safe_atoi(value, &fd) < 0 || !fdset_contains(fds, fd))
f2341e0a 3832 log_unit_debug(u, "Failed to parse netns socket value: %s", value);
613b411c 3833 else {
03e334a1 3834 safe_close((*rt)->netns_storage_socket[1]);
613b411c
LP
3835 (*rt)->netns_storage_socket[1] = fdset_remove(fds, fd);
3836 }
3837 } else
3838 return 0;
3839
3840 return 1;
3841}
3842
3843static void *remove_tmpdir_thread(void *p) {
3844 _cleanup_free_ char *path = p;
3845
c6878637 3846 (void) rm_rf(path, REMOVE_ROOT|REMOVE_PHYSICAL);
613b411c
LP
3847 return NULL;
3848}
3849
3850void exec_runtime_destroy(ExecRuntime *rt) {
98b47d54
LP
3851 int r;
3852
613b411c
LP
3853 if (!rt)
3854 return;
3855
3856 /* If there are multiple users of this, let's leave the stuff around */
3857 if (rt->n_ref > 1)
3858 return;
3859
3860 if (rt->tmp_dir) {
3861 log_debug("Spawning thread to nuke %s", rt->tmp_dir);
98b47d54
LP
3862
3863 r = asynchronous_job(remove_tmpdir_thread, rt->tmp_dir);
3864 if (r < 0) {
da927ba9 3865 log_warning_errno(r, "Failed to nuke %s: %m", rt->tmp_dir);
98b47d54
LP
3866 free(rt->tmp_dir);
3867 }
3868
613b411c
LP
3869 rt->tmp_dir = NULL;
3870 }
3871
3872 if (rt->var_tmp_dir) {
3873 log_debug("Spawning thread to nuke %s", rt->var_tmp_dir);
98b47d54
LP
3874
3875 r = asynchronous_job(remove_tmpdir_thread, rt->var_tmp_dir);
3876 if (r < 0) {
da927ba9 3877 log_warning_errno(r, "Failed to nuke %s: %m", rt->var_tmp_dir);
98b47d54
LP
3878 free(rt->var_tmp_dir);
3879 }
3880
613b411c
LP
3881 rt->var_tmp_dir = NULL;
3882 }
3883
3d94f76c 3884 safe_close_pair(rt->netns_storage_socket);
613b411c
LP
3885}
3886
80876c20
LP
3887static const char* const exec_input_table[_EXEC_INPUT_MAX] = {
3888 [EXEC_INPUT_NULL] = "null",
3889 [EXEC_INPUT_TTY] = "tty",
3890 [EXEC_INPUT_TTY_FORCE] = "tty-force",
4f2d528d
LP
3891 [EXEC_INPUT_TTY_FAIL] = "tty-fail",
3892 [EXEC_INPUT_SOCKET] = "socket"
80876c20
LP
3893};
3894
8a0867d6
LP
3895DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput);
3896
94f04347 3897static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = {
80876c20 3898 [EXEC_OUTPUT_INHERIT] = "inherit",
94f04347 3899 [EXEC_OUTPUT_NULL] = "null",
80876c20 3900 [EXEC_OUTPUT_TTY] = "tty",
94f04347 3901 [EXEC_OUTPUT_SYSLOG] = "syslog",
28dbc1e8 3902 [EXEC_OUTPUT_SYSLOG_AND_CONSOLE] = "syslog+console",
9a6bca7a 3903 [EXEC_OUTPUT_KMSG] = "kmsg",
28dbc1e8 3904 [EXEC_OUTPUT_KMSG_AND_CONSOLE] = "kmsg+console",
706343f4
LP
3905 [EXEC_OUTPUT_JOURNAL] = "journal",
3906 [EXEC_OUTPUT_JOURNAL_AND_CONSOLE] = "journal+console",
4f2d528d 3907 [EXEC_OUTPUT_SOCKET] = "socket"
94f04347
LP
3908};
3909
3910DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput);
023a4f67
LP
3911
3912static const char* const exec_utmp_mode_table[_EXEC_UTMP_MODE_MAX] = {
3913 [EXEC_UTMP_INIT] = "init",
3914 [EXEC_UTMP_LOGIN] = "login",
3915 [EXEC_UTMP_USER] = "user",
3916};
3917
3918DEFINE_STRING_TABLE_LOOKUP(exec_utmp_mode, ExecUtmpMode);