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