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