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