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