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