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