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