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