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