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