Fix an error on dlog-redirection
[platform/upstream/systemd.git] / src / core / execute.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <poll.h>
6 #include <sys/eventfd.h>
7 #include <sys/ioctl.h>
8 #include <sys/mman.h>
9 #include <sys/personality.h>
10 #include <sys/prctl.h>
11 #include <sys/shm.h>
12 #include <sys/types.h>
13 #include <sys/un.h>
14 #include <unistd.h>
15 #include <utmpx.h>
16
17 #include <dlog/dlog-redirect-stdout.h>
18
19 #if HAVE_PAM
20 #include <security/pam_appl.h>
21 #endif
22
23 #if HAVE_SELINUX
24 #include <selinux/selinux.h>
25 #endif
26
27 #if HAVE_SECCOMP
28 #include <seccomp.h>
29 #endif
30
31 #if HAVE_APPARMOR
32 #include <sys/apparmor.h>
33 #endif
34
35 #include "sd-messages.h"
36
37 #include "af-list.h"
38 #include "alloc-util.h"
39 #if HAVE_APPARMOR
40 #include "apparmor-util.h"
41 #endif
42 #include "async.h"
43 #include "barrier.h"
44 #include "cap-list.h"
45 #include "capability-util.h"
46 #include "chown-recursive.h"
47 #include "cgroup-setup.h"
48 #include "cpu-set-util.h"
49 #include "def.h"
50 #include "env-file.h"
51 #include "env-util.h"
52 #include "errno-list.h"
53 #include "execute.h"
54 #include "exit-status.h"
55 #include "fd-util.h"
56 #include "format-util.h"
57 #include "fs-util.h"
58 #include "glob-util.h"
59 #include "io-util.h"
60 #include "ioprio.h"
61 #include "label.h"
62 #include "log.h"
63 #include "macro.h"
64 #include "manager.h"
65 #include "memory-util.h"
66 #include "missing_fs.h"
67 #include "mkdir.h"
68 #include "namespace.h"
69 #include "parse-util.h"
70 #include "path-util.h"
71 #include "process-util.h"
72 #include "rlimit-util.h"
73 #include "rm-rf.h"
74 #if HAVE_SECCOMP
75 #include "seccomp-util.h"
76 #endif
77 #include "securebits-util.h"
78 #include "selinux-util.h"
79 #include "signal-util.h"
80 #include "smack-util.h"
81 #include "socket-util.h"
82 #include "special.h"
83 #include "stat-util.h"
84 #include "string-table.h"
85 #include "string-util.h"
86 #include "strv.h"
87 #include "syslog-util.h"
88 #include "terminal-util.h"
89 #include "umask-util.h"
90 #include "unit.h"
91 #include "user-util.h"
92 #include "utmp-wtmp.h"
93
94 #define IDLE_TIMEOUT_USEC (5*USEC_PER_SEC)
95 #define IDLE_TIMEOUT2_USEC (1*USEC_PER_SEC)
96
97 #define SNDBUF_SIZE (8*1024*1024)
98
99 static int shift_fds(int fds[], size_t n_fds) {
100         int start, restart_from;
101
102         if (n_fds <= 0)
103                 return 0;
104
105         /* Modifies the fds array! (sorts it) */
106
107         assert(fds);
108
109         start = 0;
110         for (;;) {
111                 int i;
112
113                 restart_from = -1;
114
115                 for (i = start; i < (int) n_fds; i++) {
116                         int nfd;
117
118                         /* Already at right index? */
119                         if (fds[i] == i+3)
120                                 continue;
121
122                         nfd = fcntl(fds[i], F_DUPFD, i + 3);
123                         if (nfd < 0)
124                                 return -errno;
125
126                         safe_close(fds[i]);
127                         fds[i] = nfd;
128
129                         /* Hmm, the fd we wanted isn't free? Then
130                          * let's remember that and try again from here */
131                         if (nfd != i+3 && restart_from < 0)
132                                 restart_from = i;
133                 }
134
135                 if (restart_from < 0)
136                         break;
137
138                 start = restart_from;
139         }
140
141         return 0;
142 }
143
144 static int flags_fds(const int fds[], size_t n_socket_fds, size_t n_storage_fds, bool nonblock) {
145         size_t i, n_fds;
146         int r;
147
148         n_fds = n_socket_fds + n_storage_fds;
149         if (n_fds <= 0)
150                 return 0;
151
152         assert(fds);
153
154         /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags.
155          * O_NONBLOCK only applies to socket activation though. */
156
157         for (i = 0; i < n_fds; i++) {
158
159                 if (i < n_socket_fds) {
160                         r = fd_nonblock(fds[i], nonblock);
161                         if (r < 0)
162                                 return r;
163                 }
164
165                 /* We unconditionally drop FD_CLOEXEC from the fds,
166                  * since after all we want to pass these fds to our
167                  * children */
168
169                 r = fd_cloexec(fds[i], false);
170                 if (r < 0)
171                         return r;
172         }
173
174         return 0;
175 }
176
177 static const char *exec_context_tty_path(const ExecContext *context) {
178         assert(context);
179
180         if (context->stdio_as_fds)
181                 return NULL;
182
183         if (context->tty_path)
184                 return context->tty_path;
185
186         return "/dev/console";
187 }
188
189 static void exec_context_tty_reset(const ExecContext *context, const ExecParameters *p) {
190         const char *path;
191
192         assert(context);
193
194         path = exec_context_tty_path(context);
195
196         if (context->tty_vhangup) {
197                 if (p && p->stdin_fd >= 0)
198                         (void) terminal_vhangup_fd(p->stdin_fd);
199                 else if (path)
200                         (void) terminal_vhangup(path);
201         }
202
203         if (context->tty_reset) {
204                 if (p && p->stdin_fd >= 0)
205                         (void) reset_terminal_fd(p->stdin_fd, true);
206                 else if (path)
207                         (void) reset_terminal(path);
208         }
209
210         if (context->tty_vt_disallocate && path)
211                 (void) vt_disallocate(path);
212 }
213
214 static bool is_terminal_input(ExecInput i) {
215         return IN_SET(i,
216                       EXEC_INPUT_TTY,
217                       EXEC_INPUT_TTY_FORCE,
218                       EXEC_INPUT_TTY_FAIL);
219 }
220
221 static bool is_terminal_output(ExecOutput o) {
222         return IN_SET(o,
223                       EXEC_OUTPUT_TTY,
224                       EXEC_OUTPUT_SYSLOG_AND_CONSOLE,
225                       EXEC_OUTPUT_KMSG_AND_CONSOLE,
226                       EXEC_OUTPUT_JOURNAL_AND_CONSOLE);
227 }
228
229 static bool is_syslog_output(ExecOutput o) {
230         return IN_SET(o,
231                       EXEC_OUTPUT_SYSLOG,
232                       EXEC_OUTPUT_SYSLOG_AND_CONSOLE);
233 }
234
235 static bool is_kmsg_output(ExecOutput o) {
236         return IN_SET(o,
237                       EXEC_OUTPUT_KMSG,
238                       EXEC_OUTPUT_KMSG_AND_CONSOLE);
239 }
240
241 static bool exec_context_needs_term(const ExecContext *c) {
242         assert(c);
243
244         /* Return true if the execution context suggests we should set $TERM to something useful. */
245
246         if (is_terminal_input(c->std_input))
247                 return true;
248
249         if (is_terminal_output(c->std_output))
250                 return true;
251
252         if (is_terminal_output(c->std_error))
253                 return true;
254
255         return !!c->tty_path;
256 }
257
258 static int open_device_as(const char *devname, int flags, int nfd) {
259         int fd;
260
261         assert(nfd >= 0);
262
263         fd = open(devname, flags|O_NOCTTY);
264         if (fd < 0)
265                 return -errno;
266
267         return move_fd(fd, nfd, false);
268 }
269
270 static int open_null_as(int flags, int nfd) {
271         return open_device_as("/dev/null", flags, nfd);
272 }
273
274 static int open_kmsg_as(int flags, int nfd) {
275         return open_device_as("/dev/kmsg", flags, nfd);
276 }
277
278 static int connect_journal_socket(int fd, uid_t uid, gid_t gid) {
279         static const union sockaddr_union sa = {
280                 .un.sun_family = AF_UNIX,
281                 .un.sun_path = "/run/systemd/journal/stdout",
282         };
283         uid_t olduid = UID_INVALID;
284         gid_t oldgid = GID_INVALID;
285         int r;
286
287         if (gid_is_valid(gid)) {
288                 oldgid = getgid();
289
290                 if (setegid(gid) < 0)
291                         return -errno;
292         }
293
294         if (uid_is_valid(uid)) {
295                 olduid = getuid();
296
297                 if (seteuid(uid) < 0) {
298                         r = -errno;
299                         goto restore_gid;
300                 }
301         }
302
303         r = connect(fd, &sa.sa, SOCKADDR_UN_LEN(sa.un)) < 0 ? -errno : 0;
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_is_valid(uid))
309                 (void) seteuid(olduid);
310
311  restore_gid:
312         if (gid_is_valid(gid))
313                 (void) setegid(oldgid);
314
315         return r;
316 }
317
318 static int connect_logger_as(
319                 const Unit *unit,
320                 const ExecContext *context,
321                 const ExecParameters *params,
322                 ExecOutput output,
323                 const char *ident,
324                 int nfd,
325                 uid_t uid,
326                 gid_t gid) {
327
328         _cleanup_close_ int fd = -1;
329         int r;
330
331         assert(context);
332         assert(params);
333         assert(output < _EXEC_OUTPUT_MAX);
334         assert(ident);
335         assert(nfd >= 0);
336
337         fd = socket(AF_UNIX, SOCK_STREAM, 0);
338         if (fd < 0)
339                 return -errno;
340
341         r = connect_journal_socket(fd, uid, gid);
342         if (r < 0)
343                 return r;
344
345         if (shutdown(fd, SHUT_RD) < 0)
346                 return -errno;
347
348         (void) fd_inc_sndbuf(fd, SNDBUF_SIZE);
349
350         if (dprintf(fd,
351                 "%s\n"
352                 "%s\n"
353                 "%i\n"
354                 "%i\n"
355                 "%i\n"
356                 "%i\n"
357                 "%i\n",
358                 context->syslog_identifier ?: ident,
359                 params->flags & EXEC_PASS_LOG_UNIT ? unit->id : "",
360                 context->syslog_priority,
361                 !!context->syslog_level_prefix,
362                 is_syslog_output(output),
363                 is_kmsg_output(output),
364                 is_terminal_output(output)) < 0)
365                 return -errno;
366
367         return move_fd(TAKE_FD(fd), nfd, false);
368 }
369
370 static int open_terminal_as(const char *path, int flags, int nfd) {
371         int fd;
372
373         assert(path);
374         assert(nfd >= 0);
375
376         fd = open_terminal(path, flags | O_NOCTTY);
377         if (fd < 0)
378                 return fd;
379
380         return move_fd(fd, nfd, false);
381 }
382
383 static int acquire_path(const char *path, int flags, mode_t mode) {
384         union sockaddr_union sa = {};
385         _cleanup_close_ int fd = -1;
386         int r, salen;
387
388         assert(path);
389
390         if (IN_SET(flags & O_ACCMODE, O_WRONLY, O_RDWR))
391                 flags |= O_CREAT;
392
393         fd = open(path, flags|O_NOCTTY, mode);
394         if (fd >= 0)
395                 return TAKE_FD(fd);
396
397         if (errno != ENXIO) /* ENXIO is returned when we try to open() an AF_UNIX file system socket on Linux */
398                 return -errno;
399         if (strlen(path) >= sizeof(sa.un.sun_path)) /* Too long, can't be a UNIX socket */
400                 return -ENXIO;
401
402         /* So, it appears the specified path could be an AF_UNIX socket. Let's see if we can connect to it. */
403
404         fd = socket(AF_UNIX, SOCK_STREAM, 0);
405         if (fd < 0)
406                 return -errno;
407
408         salen = sockaddr_un_set_path(&sa.un, path);
409         if (salen < 0)
410                 return salen;
411
412         if (connect(fd, &sa.sa, salen) < 0)
413                 return errno == EINVAL ? -ENXIO : -errno; /* Propagate initial error if we get EINVAL, i.e. we have
414                                                            * indication that his wasn't an AF_UNIX socket after all */
415
416         if ((flags & O_ACCMODE) == O_RDONLY)
417                 r = shutdown(fd, SHUT_WR);
418         else if ((flags & O_ACCMODE) == O_WRONLY)
419                 r = shutdown(fd, SHUT_RD);
420         else
421                 return TAKE_FD(fd);
422         if (r < 0)
423                 return -errno;
424
425         return TAKE_FD(fd);
426 }
427
428 static int fixup_input(
429                 const ExecContext *context,
430                 int socket_fd,
431                 bool apply_tty_stdin) {
432
433         ExecInput std_input;
434
435         assert(context);
436
437         std_input = context->std_input;
438
439         if (is_terminal_input(std_input) && !apply_tty_stdin)
440                 return EXEC_INPUT_NULL;
441
442         if (std_input == EXEC_INPUT_SOCKET && socket_fd < 0)
443                 return EXEC_INPUT_NULL;
444
445         if (std_input == EXEC_INPUT_DATA && context->stdin_data_size == 0)
446                 return EXEC_INPUT_NULL;
447
448         return std_input;
449 }
450
451 static int fixup_output(ExecOutput std_output, int socket_fd) {
452
453         if (std_output == EXEC_OUTPUT_SOCKET && socket_fd < 0)
454                 return EXEC_OUTPUT_INHERIT;
455
456         return std_output;
457 }
458
459 static int setup_input(
460                 const ExecContext *context,
461                 const ExecParameters *params,
462                 int socket_fd,
463                 const int named_iofds[static 3]) {
464
465         ExecInput i;
466
467         assert(context);
468         assert(params);
469         assert(named_iofds);
470
471         if (params->stdin_fd >= 0) {
472                 if (dup2(params->stdin_fd, STDIN_FILENO) < 0)
473                         return -errno;
474
475                 /* Try to make this the controlling tty, if it is a tty, and reset it */
476                 if (isatty(STDIN_FILENO)) {
477                         (void) ioctl(STDIN_FILENO, TIOCSCTTY, context->std_input == EXEC_INPUT_TTY_FORCE);
478                         (void) reset_terminal_fd(STDIN_FILENO, true);
479                 }
480
481                 return STDIN_FILENO;
482         }
483
484         i = fixup_input(context, socket_fd, params->flags & EXEC_APPLY_TTY_STDIN);
485
486         switch (i) {
487
488         case EXEC_INPUT_NULL:
489                 return open_null_as(O_RDONLY, STDIN_FILENO);
490
491         case EXEC_INPUT_TTY:
492         case EXEC_INPUT_TTY_FORCE:
493         case EXEC_INPUT_TTY_FAIL: {
494                 int fd;
495
496                 fd = acquire_terminal(exec_context_tty_path(context),
497                                       i == EXEC_INPUT_TTY_FAIL  ? ACQUIRE_TERMINAL_TRY :
498                                       i == EXEC_INPUT_TTY_FORCE ? ACQUIRE_TERMINAL_FORCE :
499                                                                   ACQUIRE_TERMINAL_WAIT,
500                                       USEC_INFINITY);
501                 if (fd < 0)
502                         return fd;
503
504                 return move_fd(fd, STDIN_FILENO, false);
505         }
506
507         case EXEC_INPUT_SOCKET:
508                 assert(socket_fd >= 0);
509
510                 return dup2(socket_fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
511
512         case EXEC_INPUT_NAMED_FD:
513                 assert(named_iofds[STDIN_FILENO] >= 0);
514
515                 (void) fd_nonblock(named_iofds[STDIN_FILENO], false);
516                 return dup2(named_iofds[STDIN_FILENO], STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
517
518         case EXEC_INPUT_DATA: {
519                 int fd;
520
521                 fd = acquire_data_fd(context->stdin_data, context->stdin_data_size, 0);
522                 if (fd < 0)
523                         return fd;
524
525                 return move_fd(fd, STDIN_FILENO, false);
526         }
527
528         case EXEC_INPUT_FILE: {
529                 bool rw;
530                 int fd;
531
532                 assert(context->stdio_file[STDIN_FILENO]);
533
534                 rw = (context->std_output == EXEC_OUTPUT_FILE && streq_ptr(context->stdio_file[STDIN_FILENO], context->stdio_file[STDOUT_FILENO])) ||
535                         (context->std_error == EXEC_OUTPUT_FILE && streq_ptr(context->stdio_file[STDIN_FILENO], context->stdio_file[STDERR_FILENO]));
536
537                 fd = acquire_path(context->stdio_file[STDIN_FILENO], rw ? O_RDWR : O_RDONLY, 0666 & ~context->umask);
538                 if (fd < 0)
539                         return fd;
540
541                 return move_fd(fd, STDIN_FILENO, false);
542         }
543
544         default:
545                 assert_not_reached("Unknown input type");
546         }
547 }
548
549 static bool can_inherit_stderr_from_stdout(
550                 const ExecContext *context,
551                 ExecOutput o,
552                 ExecOutput e) {
553
554         assert(context);
555
556         /* Returns true, if given the specified STDERR and STDOUT output we can directly dup() the stdout fd to the
557          * stderr fd */
558
559         if (e == EXEC_OUTPUT_INHERIT)
560                 return true;
561         if (e != o)
562                 return false;
563
564         if (e == EXEC_OUTPUT_NAMED_FD)
565                 return streq_ptr(context->stdio_fdname[STDOUT_FILENO], context->stdio_fdname[STDERR_FILENO]);
566
567         if (IN_SET(e, EXEC_OUTPUT_FILE, EXEC_OUTPUT_FILE_APPEND))
568                 return streq_ptr(context->stdio_file[STDOUT_FILENO], context->stdio_file[STDERR_FILENO]);
569
570         /* Returns false if STDERR output is redirected to dlog */
571         if (IN_SET(e, EXEC_OUTPUT_DLOG, EXEC_OUTPUT_DLOG_OR_NULL, EXEC_OUTPUT_DLOG_OR_KMSG, EXEC_OUTPUT_DLOG_OR_JOURNAL))
572                 return false;
573
574         return true;
575 }
576
577 static int wire_up_dlog(int fileno, const char *ident)
578 {
579         /* NB: dlogutil has FOO* tag filtering wildcards but not *FOO
580          * therefore the STDFOO part of the final tag goes in front.
581          *
582          * The tag can nominally be longer than 128 but dlogutil will
583          * not print a longer one anyway and it's good to limit overhead */
584         char tag[128];
585         int priority;
586
587         if (fileno == STDERR_FILENO) {
588                 priority = 6; // ERROR
589                 snprintf(tag, sizeof tag, "STDERR_%s", ident);
590         } else {
591                 priority = 4; // INFO
592                 snprintf(tag, sizeof tag, "STDOUT_%s", ident);
593         }
594
595         return dlog_connect_fd(2, // SYSTEM dlog buffer (consider also 0 for generic MAIN buffer)
596                 fileno, tag, priority);
597 }
598
599 static int setup_output(
600                 const Unit *unit,
601                 const ExecContext *context,
602                 const ExecParameters *params,
603                 int fileno,
604                 int socket_fd,
605                 const int named_iofds[static 3],
606                 const char *ident,
607                 uid_t uid,
608                 gid_t gid,
609                 dev_t *journal_stream_dev,
610                 ino_t *journal_stream_ino) {
611
612         ExecOutput o;
613         ExecInput i;
614         int r;
615
616         assert(unit);
617         assert(context);
618         assert(params);
619         assert(ident);
620         assert(journal_stream_dev);
621         assert(journal_stream_ino);
622
623         if (fileno == STDOUT_FILENO && params->stdout_fd >= 0) {
624
625                 if (dup2(params->stdout_fd, STDOUT_FILENO) < 0)
626                         return -errno;
627
628                 return STDOUT_FILENO;
629         }
630
631         if (fileno == STDERR_FILENO && params->stderr_fd >= 0) {
632                 if (dup2(params->stderr_fd, STDERR_FILENO) < 0)
633                         return -errno;
634
635                 return STDERR_FILENO;
636         }
637
638         i = fixup_input(context, socket_fd, params->flags & EXEC_APPLY_TTY_STDIN);
639         o = fixup_output(context->std_output, socket_fd);
640
641         if (fileno == STDERR_FILENO) {
642                 ExecOutput e;
643                 e = fixup_output(context->std_error, socket_fd);
644
645                 /* This expects the input and output are already set up */
646
647                 /* Don't change the stderr file descriptor if we inherit all
648                  * the way and are not on a tty */
649                 if (e == EXEC_OUTPUT_INHERIT &&
650                     o == EXEC_OUTPUT_INHERIT &&
651                     i == EXEC_INPUT_NULL &&
652                     !is_terminal_input(context->std_input) &&
653                     getppid () != 1)
654                         return fileno;
655
656                 /* Duplicate from stdout if possible */
657                 if (can_inherit_stderr_from_stdout(context, o, e))
658                         return dup2(STDOUT_FILENO, fileno) < 0 ? -errno : fileno;
659
660                 o = e;
661
662         } else if (o == EXEC_OUTPUT_INHERIT) {
663                 /* If input got downgraded, inherit the original value */
664                 if (i == EXEC_INPUT_NULL && is_terminal_input(context->std_input))
665                         return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);
666
667                 /* If the input is connected to anything that's not a /dev/null or a data fd, inherit that... */
668                 if (!IN_SET(i, EXEC_INPUT_NULL, EXEC_INPUT_DATA))
669                         return dup2(STDIN_FILENO, fileno) < 0 ? -errno : fileno;
670
671                 /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */
672                 if (getppid() != 1)
673                         return fileno;
674
675                 /* We need to open /dev/null here anew, to get the right access mode. */
676                 return open_null_as(O_WRONLY, fileno);
677         }
678
679         switch (o) {
680
681         case EXEC_OUTPUT_NULL:
682                 return open_null_as(O_WRONLY, fileno);
683
684         case EXEC_OUTPUT_TTY:
685                 if (is_terminal_input(i))
686                         return dup2(STDIN_FILENO, fileno) < 0 ? -errno : fileno;
687
688                 /* We don't reset the terminal if this is just about output */
689                 return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);
690
691         case EXEC_OUTPUT_DLOG_OR_JOURNAL:
692                 r = wire_up_dlog(fileno, ident);
693                 if (r >= 0)
694                         return fileno;
695
696                 o = EXEC_OUTPUT_JOURNAL; // used inside `connect_logger_as`, but let's not involve dlog there
697                 /* fallthrough */
698
699         case EXEC_OUTPUT_SYSLOG:
700         case EXEC_OUTPUT_SYSLOG_AND_CONSOLE:
701         case EXEC_OUTPUT_KMSG:
702         case EXEC_OUTPUT_KMSG_AND_CONSOLE:
703         case EXEC_OUTPUT_JOURNAL:
704         case EXEC_OUTPUT_JOURNAL_AND_CONSOLE:
705                 r = connect_logger_as(unit, context, params, o, ident, fileno, uid, gid);
706                 if (r < 0) {
707                         log_unit_warning_errno(unit, r, "Failed to connect %s to the journal socket, ignoring: %m", fileno == STDOUT_FILENO ? "stdout" : "stderr");
708                         r = open_null_as(O_WRONLY, fileno);
709                 } else {
710                         struct stat st;
711
712                         /* If we connected this fd to the journal via a stream, patch the device/inode into the passed
713                          * parameters, but only then. This is useful so that we can set $JOURNAL_STREAM that permits
714                          * services to detect whether they are connected to the journal or not.
715                          *
716                          * If both stdout and stderr are connected to a stream then let's make sure to store the data
717                          * about STDERR as that's usually the best way to do logging. */
718
719                         if (fstat(fileno, &st) >= 0 &&
720                             (*journal_stream_ino == 0 || fileno == STDERR_FILENO)) {
721                                 *journal_stream_dev = st.st_dev;
722                                 *journal_stream_ino = st.st_ino;
723                         }
724                 }
725                 return r;
726
727         case EXEC_OUTPUT_DLOG:
728                 r = wire_up_dlog(fileno, ident);
729                 return r < 0 ? r : fileno;
730
731         case EXEC_OUTPUT_DLOG_OR_NULL:
732                 r = wire_up_dlog(fileno, ident);
733                 if (r >= 0)
734                         return fileno;
735                 else
736                         return open_null_as(O_WRONLY, fileno);
737
738         case EXEC_OUTPUT_DLOG_OR_KMSG:
739                 r = wire_up_dlog(fileno, ident);
740                 if (r >= 0)
741                         return fileno;
742                 else
743                         return open_kmsg_as(O_WRONLY, fileno);
744
745         case EXEC_OUTPUT_SOCKET:
746                 assert(socket_fd >= 0);
747
748                 return dup2(socket_fd, fileno) < 0 ? -errno : fileno;
749
750         case EXEC_OUTPUT_NAMED_FD:
751                 assert(named_iofds[fileno] >= 0);
752
753                 (void) fd_nonblock(named_iofds[fileno], false);
754                 return dup2(named_iofds[fileno], fileno) < 0 ? -errno : fileno;
755
756         case EXEC_OUTPUT_FILE:
757         case EXEC_OUTPUT_FILE_APPEND: {
758                 bool rw;
759                 int fd, flags;
760
761                 assert(context->stdio_file[fileno]);
762
763                 rw = context->std_input == EXEC_INPUT_FILE &&
764                         streq_ptr(context->stdio_file[fileno], context->stdio_file[STDIN_FILENO]);
765
766                 if (rw)
767                         return dup2(STDIN_FILENO, fileno) < 0 ? -errno : fileno;
768
769                 flags = O_WRONLY;
770                 if (o == EXEC_OUTPUT_FILE_APPEND)
771                         flags |= O_APPEND;
772
773                 fd = acquire_path(context->stdio_file[fileno], flags, 0666 & ~context->umask);
774                 if (fd < 0)
775                         return fd;
776
777                 return move_fd(fd, fileno, 0);
778         }
779
780         default:
781                 assert_not_reached("Unknown error type");
782         }
783 }
784
785 static int chown_terminal(int fd, uid_t uid) {
786         int r;
787
788         assert(fd >= 0);
789
790         /* Before we chown/chmod the TTY, let's ensure this is actually a tty */
791         if (isatty(fd) < 1) {
792                 if (IN_SET(errno, EINVAL, ENOTTY))
793                         return 0; /* not a tty */
794
795                 return -errno;
796         }
797
798         /* This might fail. What matters are the results. */
799         r = fchmod_and_chown(fd, TTY_MODE, uid, -1);
800         if (r < 0)
801                 return r;
802
803         return 1;
804 }
805
806 static int setup_confirm_stdio(const char *vc, int *_saved_stdin, int *_saved_stdout) {
807         _cleanup_close_ int fd = -1, saved_stdin = -1, saved_stdout = -1;
808         int r;
809
810         assert(_saved_stdin);
811         assert(_saved_stdout);
812
813         saved_stdin = fcntl(STDIN_FILENO, F_DUPFD, 3);
814         if (saved_stdin < 0)
815                 return -errno;
816
817         saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD, 3);
818         if (saved_stdout < 0)
819                 return -errno;
820
821         fd = acquire_terminal(vc, ACQUIRE_TERMINAL_WAIT, DEFAULT_CONFIRM_USEC);
822         if (fd < 0)
823                 return fd;
824
825         r = chown_terminal(fd, getuid());
826         if (r < 0)
827                 return r;
828
829         r = reset_terminal_fd(fd, true);
830         if (r < 0)
831                 return r;
832
833         r = rearrange_stdio(fd, fd, STDERR_FILENO);
834         fd = -1;
835         if (r < 0)
836                 return r;
837
838         *_saved_stdin = saved_stdin;
839         *_saved_stdout = saved_stdout;
840
841         saved_stdin = saved_stdout = -1;
842
843         return 0;
844 }
845
846 static void write_confirm_error_fd(int err, int fd, const Unit *u) {
847         assert(err < 0);
848
849         if (err == -ETIMEDOUT)
850                 dprintf(fd, "Confirmation question timed out for %s, assuming positive response.\n", u->id);
851         else {
852                 errno = -err;
853                 dprintf(fd, "Couldn't ask confirmation for %s: %m, assuming positive response.\n", u->id);
854         }
855 }
856
857 static void write_confirm_error(int err, const char *vc, const Unit *u) {
858         _cleanup_close_ int fd = -1;
859
860         assert(vc);
861
862         fd = open_terminal(vc, O_WRONLY|O_NOCTTY|O_CLOEXEC);
863         if (fd < 0)
864                 return;
865
866         write_confirm_error_fd(err, fd, u);
867 }
868
869 static int restore_confirm_stdio(int *saved_stdin, int *saved_stdout) {
870         int r = 0;
871
872         assert(saved_stdin);
873         assert(saved_stdout);
874
875         release_terminal();
876
877         if (*saved_stdin >= 0)
878                 if (dup2(*saved_stdin, STDIN_FILENO) < 0)
879                         r = -errno;
880
881         if (*saved_stdout >= 0)
882                 if (dup2(*saved_stdout, STDOUT_FILENO) < 0)
883                         r = -errno;
884
885         *saved_stdin = safe_close(*saved_stdin);
886         *saved_stdout = safe_close(*saved_stdout);
887
888         return r;
889 }
890
891 enum {
892         CONFIRM_PRETEND_FAILURE = -1,
893         CONFIRM_PRETEND_SUCCESS =  0,
894         CONFIRM_EXECUTE = 1,
895 };
896
897 static int ask_for_confirmation(const char *vc, Unit *u, const char *cmdline) {
898         int saved_stdout = -1, saved_stdin = -1, r;
899         _cleanup_free_ char *e = NULL;
900         char c;
901
902         /* For any internal errors, assume a positive response. */
903         r = setup_confirm_stdio(vc, &saved_stdin, &saved_stdout);
904         if (r < 0) {
905                 write_confirm_error(r, vc, u);
906                 return CONFIRM_EXECUTE;
907         }
908
909         /* confirm_spawn might have been disabled while we were sleeping. */
910         if (manager_is_confirm_spawn_disabled(u->manager)) {
911                 r = 1;
912                 goto restore_stdio;
913         }
914
915         e = ellipsize(cmdline, 60, 100);
916         if (!e) {
917                 log_oom();
918                 r = CONFIRM_EXECUTE;
919                 goto restore_stdio;
920         }
921
922         for (;;) {
923                 r = ask_char(&c, "yfshiDjcn", "Execute %s? [y, f, s â€“ h for help] ", e);
924                 if (r < 0) {
925                         write_confirm_error_fd(r, STDOUT_FILENO, u);
926                         r = CONFIRM_EXECUTE;
927                         goto restore_stdio;
928                 }
929
930                 switch (c) {
931                 case 'c':
932                         printf("Resuming normal execution.\n");
933                         manager_disable_confirm_spawn();
934                         r = 1;
935                         break;
936                 case 'D':
937                         unit_dump(u, stdout, "  ");
938                         continue; /* ask again */
939                 case 'f':
940                         printf("Failing execution.\n");
941                         r = CONFIRM_PRETEND_FAILURE;
942                         break;
943                 case 'h':
944                         printf("  c - continue, proceed without asking anymore\n"
945                                "  D - dump, show the state of the unit\n"
946                                "  f - fail, don't execute the command and pretend it failed\n"
947                                "  h - help\n"
948                                "  i - info, show a short summary of the unit\n"
949                                "  j - jobs, show jobs that are in progress\n"
950                                "  s - skip, don't execute the command and pretend it succeeded\n"
951                                "  y - yes, execute the command\n");
952                         continue; /* ask again */
953                 case 'i':
954                         printf("  Description: %s\n"
955                                "  Unit:        %s\n"
956                                "  Command:     %s\n",
957                                u->id, u->description, cmdline);
958                         continue; /* ask again */
959                 case 'j':
960                         manager_dump_jobs(u->manager, stdout, "  ");
961                         continue; /* ask again */
962                 case 'n':
963                         /* 'n' was removed in favor of 'f'. */
964                         printf("Didn't understand 'n', did you mean 'f'?\n");
965                         continue; /* ask again */
966                 case 's':
967                         printf("Skipping execution.\n");
968                         r = CONFIRM_PRETEND_SUCCESS;
969                         break;
970                 case 'y':
971                         r = CONFIRM_EXECUTE;
972                         break;
973                 default:
974                         assert_not_reached("Unhandled choice");
975                 }
976                 break;
977         }
978
979 restore_stdio:
980         restore_confirm_stdio(&saved_stdin, &saved_stdout);
981         return r;
982 }
983
984 static int get_fixed_user(const ExecContext *c, const char **user,
985                           uid_t *uid, gid_t *gid,
986                           const char **home, const char **shell) {
987         int r;
988         const char *name;
989
990         assert(c);
991
992         if (!c->user)
993                 return 0;
994
995         /* Note that we don't set $HOME or $SHELL if they are not particularly enlightening anyway
996          * (i.e. are "/" or "/bin/nologin"). */
997
998         name = c->user;
999         r = get_user_creds(&name, uid, gid, home, shell, USER_CREDS_CLEAN);
1000         if (r < 0)
1001                 return r;
1002
1003         *user = name;
1004         return 0;
1005 }
1006
1007 static int get_fixed_group(const ExecContext *c, const char **group, gid_t *gid) {
1008         int r;
1009         const char *name;
1010
1011         assert(c);
1012
1013         if (!c->group)
1014                 return 0;
1015
1016         name = c->group;
1017         r = get_group_creds(&name, gid, 0);
1018         if (r < 0)
1019                 return r;
1020
1021         *group = name;
1022         return 0;
1023 }
1024
1025 static int get_supplementary_groups(const ExecContext *c, const char *user,
1026                                     const char *group, gid_t gid,
1027                                     gid_t **supplementary_gids, int *ngids) {
1028         char **i;
1029         int r, k = 0;
1030         int ngroups_max;
1031         bool keep_groups = false;
1032         gid_t *groups = NULL;
1033         _cleanup_free_ gid_t *l_gids = NULL;
1034
1035         assert(c);
1036
1037         /*
1038          * If user is given, then lookup GID and supplementary groups list.
1039          * We avoid NSS lookups for gid=0. Also we have to initialize groups
1040          * here and as early as possible so we keep the list of supplementary
1041          * groups of the caller.
1042          */
1043         if (user && gid_is_valid(gid) && gid != 0) {
1044                 /* First step, initialize groups from /etc/groups */
1045                 if (initgroups(user, gid) < 0)
1046                         return -errno;
1047
1048                 keep_groups = true;
1049         }
1050
1051         if (strv_isempty(c->supplementary_groups))
1052                 return 0;
1053
1054         /*
1055          * If SupplementaryGroups= was passed then NGROUPS_MAX has to
1056          * be positive, otherwise fail.
1057          */
1058         errno = 0;
1059         ngroups_max = (int) sysconf(_SC_NGROUPS_MAX);
1060         if (ngroups_max <= 0)
1061                 return errno_or_else(EOPNOTSUPP);
1062
1063         l_gids = new(gid_t, ngroups_max);
1064         if (!l_gids)
1065                 return -ENOMEM;
1066
1067         if (keep_groups) {
1068                 /*
1069                  * Lookup the list of groups that the user belongs to, we
1070                  * avoid NSS lookups here too for gid=0.
1071                  */
1072                 k = ngroups_max;
1073                 if (getgrouplist(user, gid, l_gids, &k) < 0)
1074                         return -EINVAL;
1075         } else
1076                 k = 0;
1077
1078         STRV_FOREACH(i, c->supplementary_groups) {
1079                 const char *g;
1080
1081                 if (k >= ngroups_max)
1082                         return -E2BIG;
1083
1084                 g = *i;
1085                 r = get_group_creds(&g, l_gids+k, 0);
1086                 if (r < 0)
1087                         return r;
1088
1089                 k++;
1090         }
1091
1092         /*
1093          * Sets ngids to zero to drop all supplementary groups, happens
1094          * when we are under root and SupplementaryGroups= is empty.
1095          */
1096         if (k == 0) {
1097                 *ngids = 0;
1098                 return 0;
1099         }
1100
1101         /* Otherwise get the final list of supplementary groups */
1102         groups = memdup(l_gids, sizeof(gid_t) * k);
1103         if (!groups)
1104                 return -ENOMEM;
1105
1106         *supplementary_gids = groups;
1107         *ngids = k;
1108
1109         groups = NULL;
1110
1111         return 0;
1112 }
1113
1114 static int enforce_groups(gid_t gid, const gid_t *supplementary_gids, int ngids) {
1115         int r;
1116
1117         /* Handle SupplementaryGroups= if it is not empty */
1118         if (ngids > 0) {
1119                 r = maybe_setgroups(ngids, supplementary_gids);
1120                 if (r < 0)
1121                         return r;
1122         }
1123
1124         if (gid_is_valid(gid)) {
1125                 /* Then set our gids */
1126                 if (setresgid(gid, gid, gid) < 0)
1127                         return -errno;
1128         }
1129
1130         return 0;
1131 }
1132
1133 static int enforce_user(const ExecContext *context, uid_t uid) {
1134         assert(context);
1135
1136         if (!uid_is_valid(uid))
1137                 return 0;
1138
1139         /* Sets (but doesn't look up) the uid and make sure we keep the
1140          * capabilities while doing so. */
1141
1142         if (context->capabilities || context->capability_ambient_set != 0) {
1143
1144                 /* First step: If we need to keep capabilities but
1145                  * drop privileges we need to make sure we keep our
1146                  * caps, while we drop privileges. */
1147                 if (uid != 0) {
1148                         int sb = context->secure_bits | 1<<SECURE_KEEP_CAPS;
1149
1150                         if (prctl(PR_GET_SECUREBITS) != sb)
1151                                 if (prctl(PR_SET_SECUREBITS, sb) < 0)
1152                                         return -errno;
1153                 }
1154                 /* Second step: set the capabilities. This will reduce
1155                  * the capabilities to the minimum we need. */
1156
1157                 if (context->capabilities) {
1158                         _cleanup_cap_free_ cap_t d = NULL;
1159                         static const cap_value_t bits[] = {
1160                                 CAP_SETUID,   /* Necessary so that we can run setresuid() below */
1161                                 CAP_SETPCAP   /* Necessary so that we can set PR_SET_SECUREBITS later on */
1162                         };
1163
1164                         d = cap_dup(context->capabilities);
1165                         if (!d)
1166                                 return -errno;
1167
1168                         if (cap_set_flag(d, CAP_EFFECTIVE, ELEMENTSOF(bits), bits, CAP_SET) < 0 ||
1169                             cap_set_flag(d, CAP_PERMITTED, ELEMENTSOF(bits), bits, CAP_SET) < 0)
1170                                 return -errno;
1171
1172                         if (cap_set_proc(d) < 0)
1173                                 return -errno;
1174                 }
1175         }
1176
1177         /* Third step: actually set the uids */
1178         if (setresuid(uid, uid, uid) < 0)
1179                 return -errno;
1180
1181         /* At this point we should have all necessary capabilities but
1182            are otherwise a normal user. However, the caps might got
1183            corrupted due to the setresuid() so we need clean them up
1184            later. This is done outside of this call. */
1185
1186         return 0;
1187 }
1188
1189 #if HAVE_PAM
1190
1191 static int null_conv(
1192                 int num_msg,
1193                 const struct pam_message **msg,
1194                 struct pam_response **resp,
1195                 void *appdata_ptr) {
1196
1197         /* We don't support conversations */
1198
1199         return PAM_CONV_ERR;
1200 }
1201
1202 #endif
1203
1204 static int setup_pam(
1205                 const char *name,
1206                 const char *user,
1207                 uid_t uid,
1208                 gid_t gid,
1209                 const char *tty,
1210                 char ***env,
1211                 int fds[], size_t n_fds) {
1212
1213 #if HAVE_PAM
1214
1215         static const struct pam_conv conv = {
1216                 .conv = null_conv,
1217                 .appdata_ptr = NULL
1218         };
1219
1220         _cleanup_(barrier_destroy) Barrier barrier = BARRIER_NULL;
1221         pam_handle_t *handle = NULL;
1222         sigset_t old_ss;
1223         int pam_code = PAM_SUCCESS, r;
1224         char **nv, **e = NULL;
1225         bool close_session = false;
1226         pid_t pam_pid = 0, parent_pid;
1227         int flags = 0;
1228
1229         assert(name);
1230         assert(user);
1231         assert(env);
1232
1233         /* We set up PAM in the parent process, then fork. The child
1234          * will then stay around until killed via PR_GET_PDEATHSIG or
1235          * systemd via the cgroup logic. It will then remove the PAM
1236          * session again. The parent process will exec() the actual
1237          * daemon. We do things this way to ensure that the main PID
1238          * of the daemon is the one we initially fork()ed. */
1239
1240         r = barrier_create(&barrier);
1241         if (r < 0)
1242                 goto fail;
1243
1244         if (log_get_max_level() < LOG_DEBUG)
1245                 flags |= PAM_SILENT;
1246
1247         pam_code = pam_start(name, user, &conv, &handle);
1248         if (pam_code != PAM_SUCCESS) {
1249                 handle = NULL;
1250                 goto fail;
1251         }
1252
1253         if (!tty) {
1254                 _cleanup_free_ char *q = NULL;
1255
1256                 /* Hmm, so no TTY was explicitly passed, but an fd passed to us directly might be a TTY. Let's figure
1257                  * out if that's the case, and read the TTY off it. */
1258
1259                 if (getttyname_malloc(STDIN_FILENO, &q) >= 0)
1260                         tty = strjoina("/dev/", q);
1261         }
1262
1263         if (tty) {
1264                 pam_code = pam_set_item(handle, PAM_TTY, tty);
1265                 if (pam_code != PAM_SUCCESS)
1266                         goto fail;
1267         }
1268
1269         STRV_FOREACH(nv, *env) {
1270                 pam_code = pam_putenv(handle, *nv);
1271                 if (pam_code != PAM_SUCCESS)
1272                         goto fail;
1273         }
1274
1275         pam_code = pam_acct_mgmt(handle, flags);
1276         if (pam_code != PAM_SUCCESS)
1277                 goto fail;
1278
1279         pam_code = pam_open_session(handle, flags);
1280         if (pam_code != PAM_SUCCESS)
1281                 goto fail;
1282
1283         close_session = true;
1284
1285         e = pam_getenvlist(handle);
1286         if (!e) {
1287                 pam_code = PAM_BUF_ERR;
1288                 goto fail;
1289         }
1290
1291         /* Block SIGTERM, so that we know that it won't get lost in
1292          * the child */
1293
1294         assert_se(sigprocmask_many(SIG_BLOCK, &old_ss, SIGTERM, -1) >= 0);
1295
1296         parent_pid = getpid_cached();
1297
1298         r = safe_fork("(sd-pam)", 0, &pam_pid);
1299         if (r < 0)
1300                 goto fail;
1301         if (r == 0) {
1302                 int sig, ret = EXIT_PAM;
1303
1304                 /* The child's job is to reset the PAM session on
1305                  * termination */
1306                 barrier_set_role(&barrier, BARRIER_CHILD);
1307
1308                 /* Make sure we don't keep open the passed fds in this child. We assume that otherwise only those fds
1309                  * are open here that have been opened by PAM. */
1310                 (void) close_many(fds, n_fds);
1311
1312                 /* Drop privileges - we don't need any to pam_close_session
1313                  * and this will make PR_SET_PDEATHSIG work in most cases.
1314                  * If this fails, ignore the error - but expect sd-pam threads
1315                  * to fail to exit normally */
1316
1317                 r = maybe_setgroups(0, NULL);
1318                 if (r < 0)
1319                         log_warning_errno(r, "Failed to setgroups() in sd-pam: %m");
1320                 if (setresgid(gid, gid, gid) < 0)
1321                         log_warning_errno(errno, "Failed to setresgid() in sd-pam: %m");
1322                 if (setresuid(uid, uid, uid) < 0)
1323                         log_warning_errno(errno, "Failed to setresuid() in sd-pam: %m");
1324
1325                 (void) ignore_signals(SIGPIPE, -1);
1326
1327                 /* Wait until our parent died. This will only work if
1328                  * the above setresuid() succeeds, otherwise the kernel
1329                  * will not allow unprivileged parents kill their privileged
1330                  * children this way. We rely on the control groups kill logic
1331                  * to do the rest for us. */
1332                 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
1333                         goto child_finish;
1334
1335                 /* Tell the parent that our setup is done. This is especially
1336                  * important regarding dropping privileges. Otherwise, unit
1337                  * setup might race against our setresuid(2) call.
1338                  *
1339                  * If the parent aborted, we'll detect this below, hence ignore
1340                  * return failure here. */
1341                 (void) barrier_place(&barrier);
1342
1343                 /* Check if our parent process might already have died? */
1344                 if (getppid() == parent_pid) {
1345                         sigset_t ss;
1346
1347                         assert_se(sigemptyset(&ss) >= 0);
1348                         assert_se(sigaddset(&ss, SIGTERM) >= 0);
1349
1350                         for (;;) {
1351                                 if (sigwait(&ss, &sig) < 0) {
1352                                         if (errno == EINTR)
1353                                                 continue;
1354
1355                                         goto child_finish;
1356                                 }
1357
1358                                 assert(sig == SIGTERM);
1359                                 break;
1360                         }
1361                 }
1362
1363                 /* If our parent died we'll end the session */
1364                 if (getppid() != parent_pid) {
1365                         pam_code = pam_close_session(handle, flags);
1366                         if (pam_code != PAM_SUCCESS)
1367                                 goto child_finish;
1368                 }
1369
1370                 ret = 0;
1371
1372         child_finish:
1373                 pam_end(handle, pam_code | flags);
1374                 _exit(ret);
1375         }
1376
1377         barrier_set_role(&barrier, BARRIER_PARENT);
1378
1379         /* If the child was forked off successfully it will do all the
1380          * cleanups, so forget about the handle here. */
1381         handle = NULL;
1382
1383         /* Unblock SIGTERM again in the parent */
1384         assert_se(sigprocmask(SIG_SETMASK, &old_ss, NULL) >= 0);
1385
1386         /* We close the log explicitly here, since the PAM modules
1387          * might have opened it, but we don't want this fd around. */
1388         closelog();
1389
1390         /* Synchronously wait for the child to initialize. We don't care for
1391          * errors as we cannot recover. However, warn loudly if it happens. */
1392         if (!barrier_place_and_sync(&barrier))
1393                 log_error("PAM initialization failed");
1394
1395         return strv_free_and_replace(*env, e);
1396
1397 fail:
1398         if (pam_code != PAM_SUCCESS) {
1399                 log_error("PAM failed: %s", pam_strerror(handle, pam_code));
1400                 r = -EPERM;  /* PAM errors do not map to errno */
1401         } else
1402                 log_error_errno(r, "PAM failed: %m");
1403
1404         if (handle) {
1405                 if (close_session)
1406                         pam_code = pam_close_session(handle, flags);
1407
1408                 pam_end(handle, pam_code | flags);
1409         }
1410
1411         strv_free(e);
1412         closelog();
1413
1414         return r;
1415 #else
1416         return 0;
1417 #endif
1418 }
1419
1420 static void rename_process_from_path(const char *path) {
1421         char process_name[11];
1422         const char *p;
1423         size_t l;
1424
1425         /* This resulting string must fit in 10 chars (i.e. the length
1426          * of "/sbin/init") to look pretty in /bin/ps */
1427
1428         p = basename(path);
1429         if (isempty(p)) {
1430                 rename_process("(...)");
1431                 return;
1432         }
1433
1434         l = strlen(p);
1435         if (l > 8) {
1436                 /* The end of the process name is usually more
1437                  * interesting, since the first bit might just be
1438                  * "systemd-" */
1439                 p = p + l - 8;
1440                 l = 8;
1441         }
1442
1443         process_name[0] = '(';
1444         memcpy(process_name+1, p, l);
1445         process_name[1+l] = ')';
1446         process_name[1+l+1] = 0;
1447
1448         rename_process(process_name);
1449 }
1450
1451 static bool context_has_address_families(const ExecContext *c) {
1452         assert(c);
1453
1454         return c->address_families_whitelist ||
1455                 !set_isempty(c->address_families);
1456 }
1457
1458 static bool context_has_syscall_filters(const ExecContext *c) {
1459         assert(c);
1460
1461         return c->syscall_whitelist ||
1462                 !hashmap_isempty(c->syscall_filter);
1463 }
1464
1465 static bool context_has_no_new_privileges(const ExecContext *c) {
1466         assert(c);
1467
1468         if (c->no_new_privileges)
1469                 return true;
1470
1471         if (have_effective_cap(CAP_SYS_ADMIN)) /* if we are privileged, we don't need NNP */
1472                 return false;
1473
1474         /* We need NNP if we have any form of seccomp and are unprivileged */
1475         return context_has_address_families(c) ||
1476                 c->memory_deny_write_execute ||
1477                 c->restrict_realtime ||
1478                 c->restrict_suid_sgid ||
1479                 exec_context_restrict_namespaces_set(c) ||
1480                 c->protect_kernel_tunables ||
1481                 c->protect_kernel_modules ||
1482                 c->protect_kernel_logs ||
1483                 c->private_devices ||
1484                 context_has_syscall_filters(c) ||
1485                 !set_isempty(c->syscall_archs) ||
1486                 c->lock_personality ||
1487                 c->protect_hostname;
1488 }
1489
1490 #if HAVE_SECCOMP
1491
1492 static bool skip_seccomp_unavailable(const Unit* u, const char* msg) {
1493
1494         if (is_seccomp_available())
1495                 return false;
1496
1497         log_unit_debug(u, "SECCOMP features not detected in the kernel, skipping %s", msg);
1498         return true;
1499 }
1500
1501 static int apply_syscall_filter(const Unit* u, const ExecContext *c, bool needs_ambient_hack) {
1502         uint32_t negative_action, default_action, action;
1503         int r;
1504
1505         assert(u);
1506         assert(c);
1507
1508         if (!context_has_syscall_filters(c))
1509                 return 0;
1510
1511         if (skip_seccomp_unavailable(u, "SystemCallFilter="))
1512                 return 0;
1513
1514         negative_action = c->syscall_errno == 0 ? scmp_act_kill_process() : SCMP_ACT_ERRNO(c->syscall_errno);
1515
1516         if (c->syscall_whitelist) {
1517                 default_action = negative_action;
1518                 action = SCMP_ACT_ALLOW;
1519         } else {
1520                 default_action = SCMP_ACT_ALLOW;
1521                 action = negative_action;
1522         }
1523
1524         if (needs_ambient_hack) {
1525                 r = seccomp_filter_set_add(c->syscall_filter, c->syscall_whitelist, syscall_filter_sets + SYSCALL_FILTER_SET_SETUID);
1526                 if (r < 0)
1527                         return r;
1528         }
1529
1530         return seccomp_load_syscall_filter_set_raw(default_action, c->syscall_filter, action, false);
1531 }
1532
1533 static int apply_syscall_archs(const Unit *u, const ExecContext *c) {
1534         assert(u);
1535         assert(c);
1536
1537         if (set_isempty(c->syscall_archs))
1538                 return 0;
1539
1540         if (skip_seccomp_unavailable(u, "SystemCallArchitectures="))
1541                 return 0;
1542
1543         return seccomp_restrict_archs(c->syscall_archs);
1544 }
1545
1546 static int apply_address_families(const Unit* u, const ExecContext *c) {
1547         assert(u);
1548         assert(c);
1549
1550         if (!context_has_address_families(c))
1551                 return 0;
1552
1553         if (skip_seccomp_unavailable(u, "RestrictAddressFamilies="))
1554                 return 0;
1555
1556         return seccomp_restrict_address_families(c->address_families, c->address_families_whitelist);
1557 }
1558
1559 static int apply_memory_deny_write_execute(const Unit* u, const ExecContext *c) {
1560         assert(u);
1561         assert(c);
1562
1563         if (!c->memory_deny_write_execute)
1564                 return 0;
1565
1566         if (skip_seccomp_unavailable(u, "MemoryDenyWriteExecute="))
1567                 return 0;
1568
1569         return seccomp_memory_deny_write_execute();
1570 }
1571
1572 static int apply_restrict_realtime(const Unit* u, const ExecContext *c) {
1573         assert(u);
1574         assert(c);
1575
1576         if (!c->restrict_realtime)
1577                 return 0;
1578
1579         if (skip_seccomp_unavailable(u, "RestrictRealtime="))
1580                 return 0;
1581
1582         return seccomp_restrict_realtime();
1583 }
1584
1585 static int apply_restrict_suid_sgid(const Unit* u, const ExecContext *c) {
1586         assert(u);
1587         assert(c);
1588
1589         if (!c->restrict_suid_sgid)
1590                 return 0;
1591
1592         if (skip_seccomp_unavailable(u, "RestrictSUIDSGID="))
1593                 return 0;
1594
1595         return seccomp_restrict_suid_sgid();
1596 }
1597
1598 static int apply_protect_sysctl(const Unit *u, const ExecContext *c) {
1599         assert(u);
1600         assert(c);
1601
1602         /* Turn off the legacy sysctl() system call. Many distributions turn this off while building the kernel, but
1603          * let's protect even those systems where this is left on in the kernel. */
1604
1605         if (!c->protect_kernel_tunables)
1606                 return 0;
1607
1608         if (skip_seccomp_unavailable(u, "ProtectKernelTunables="))
1609                 return 0;
1610
1611         return seccomp_protect_sysctl();
1612 }
1613
1614 static int apply_protect_kernel_modules(const Unit *u, const ExecContext *c) {
1615         assert(u);
1616         assert(c);
1617
1618         /* Turn off module syscalls on ProtectKernelModules=yes */
1619
1620         if (!c->protect_kernel_modules)
1621                 return 0;
1622
1623         if (skip_seccomp_unavailable(u, "ProtectKernelModules="))
1624                 return 0;
1625
1626         return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_MODULE, SCMP_ACT_ERRNO(EPERM), false);
1627 }
1628
1629 static int apply_protect_kernel_logs(const Unit *u, const ExecContext *c) {
1630         assert(u);
1631         assert(c);
1632
1633         if (!c->protect_kernel_logs)
1634                 return 0;
1635
1636         if (skip_seccomp_unavailable(u, "ProtectKernelLogs="))
1637                 return 0;
1638
1639         return seccomp_protect_syslog();
1640 }
1641
1642 static int apply_private_devices(const Unit *u, const ExecContext *c) {
1643         assert(u);
1644         assert(c);
1645
1646         /* If PrivateDevices= is set, also turn off iopl and all @raw-io syscalls. */
1647
1648         if (!c->private_devices)
1649                 return 0;
1650
1651         if (skip_seccomp_unavailable(u, "PrivateDevices="))
1652                 return 0;
1653
1654         return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_RAW_IO, SCMP_ACT_ERRNO(EPERM), false);
1655 }
1656
1657 static int apply_restrict_namespaces(const Unit *u, const ExecContext *c) {
1658         assert(u);
1659         assert(c);
1660
1661         if (!exec_context_restrict_namespaces_set(c))
1662                 return 0;
1663
1664         if (skip_seccomp_unavailable(u, "RestrictNamespaces="))
1665                 return 0;
1666
1667         return seccomp_restrict_namespaces(c->restrict_namespaces);
1668 }
1669
1670 static int apply_lock_personality(const Unit* u, const ExecContext *c) {
1671         unsigned long personality;
1672         int r;
1673
1674         assert(u);
1675         assert(c);
1676
1677         if (!c->lock_personality)
1678                 return 0;
1679
1680         if (skip_seccomp_unavailable(u, "LockPersonality="))
1681                 return 0;
1682
1683         personality = c->personality;
1684
1685         /* If personality is not specified, use either PER_LINUX or PER_LINUX32 depending on what is currently set. */
1686         if (personality == PERSONALITY_INVALID) {
1687
1688                 r = opinionated_personality(&personality);
1689                 if (r < 0)
1690                         return r;
1691         }
1692
1693         return seccomp_lock_personality(personality);
1694 }
1695
1696 #endif
1697
1698 static void do_idle_pipe_dance(int idle_pipe[static 4]) {
1699         assert(idle_pipe);
1700
1701         idle_pipe[1] = safe_close(idle_pipe[1]);
1702         idle_pipe[2] = safe_close(idle_pipe[2]);
1703
1704         if (idle_pipe[0] >= 0) {
1705                 int r;
1706
1707                 r = fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT_USEC);
1708
1709                 if (idle_pipe[3] >= 0 && r == 0 /* timeout */) {
1710                         ssize_t n;
1711
1712                         /* Signal systemd that we are bored and want to continue. */
1713                         n = write(idle_pipe[3], "x", 1);
1714                         if (n > 0)
1715                                 /* Wait for systemd to react to the signal above. */
1716                                 (void) fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT2_USEC);
1717                 }
1718
1719                 idle_pipe[0] = safe_close(idle_pipe[0]);
1720
1721         }
1722
1723         idle_pipe[3] = safe_close(idle_pipe[3]);
1724 }
1725
1726 static const char *exec_directory_env_name_to_string(ExecDirectoryType t);
1727
1728 static int build_environment(
1729                 const Unit *u,
1730                 const ExecContext *c,
1731                 const ExecParameters *p,
1732                 size_t n_fds,
1733                 const char *home,
1734                 const char *username,
1735                 const char *shell,
1736                 dev_t journal_stream_dev,
1737                 ino_t journal_stream_ino,
1738                 char ***ret) {
1739
1740         _cleanup_strv_free_ char **our_env = NULL;
1741         ExecDirectoryType t;
1742         size_t n_env = 0;
1743         char *x;
1744
1745         assert(u);
1746         assert(c);
1747         assert(p);
1748         assert(ret);
1749
1750         our_env = new0(char*, 14 + _EXEC_DIRECTORY_TYPE_MAX);
1751         if (!our_env)
1752                 return -ENOMEM;
1753
1754         if (n_fds > 0) {
1755                 _cleanup_free_ char *joined = NULL;
1756
1757                 if (asprintf(&x, "LISTEN_PID="PID_FMT, getpid_cached()) < 0)
1758                         return -ENOMEM;
1759                 our_env[n_env++] = x;
1760
1761                 if (asprintf(&x, "LISTEN_FDS=%zu", n_fds) < 0)
1762                         return -ENOMEM;
1763                 our_env[n_env++] = x;
1764
1765                 joined = strv_join(p->fd_names, ":");
1766                 if (!joined)
1767                         return -ENOMEM;
1768
1769                 x = strjoin("LISTEN_FDNAMES=", joined);
1770                 if (!x)
1771                         return -ENOMEM;
1772                 our_env[n_env++] = x;
1773         }
1774
1775         if ((p->flags & EXEC_SET_WATCHDOG) && p->watchdog_usec > 0) {
1776                 if (asprintf(&x, "WATCHDOG_PID="PID_FMT, getpid_cached()) < 0)
1777                         return -ENOMEM;
1778                 our_env[n_env++] = x;
1779
1780                 if (asprintf(&x, "WATCHDOG_USEC="USEC_FMT, p->watchdog_usec) < 0)
1781                         return -ENOMEM;
1782                 our_env[n_env++] = x;
1783         }
1784
1785         /* If this is D-Bus, tell the nss-systemd module, since it relies on being able to use D-Bus look up dynamic
1786          * users via PID 1, possibly dead-locking the dbus daemon. This way it will not use D-Bus to resolve names, but
1787          * check the database directly. */
1788         if (p->flags & EXEC_NSS_BYPASS_BUS) {
1789                 x = strdup("SYSTEMD_NSS_BYPASS_BUS=1");
1790                 if (!x)
1791                         return -ENOMEM;
1792                 our_env[n_env++] = x;
1793         }
1794
1795         if (home) {
1796                 x = strjoin("HOME=", home);
1797                 if (!x)
1798                         return -ENOMEM;
1799
1800                 path_simplify(x + 5, true);
1801                 our_env[n_env++] = x;
1802         }
1803
1804         if (username) {
1805                 x = strjoin("LOGNAME=", username);
1806                 if (!x)
1807                         return -ENOMEM;
1808                 our_env[n_env++] = x;
1809
1810                 x = strjoin("USER=", username);
1811                 if (!x)
1812                         return -ENOMEM;
1813                 our_env[n_env++] = x;
1814         }
1815
1816         if (shell) {
1817                 x = strjoin("SHELL=", shell);
1818                 if (!x)
1819                         return -ENOMEM;
1820
1821                 path_simplify(x + 6, true);
1822                 our_env[n_env++] = x;
1823         }
1824
1825         if (!sd_id128_is_null(u->invocation_id)) {
1826                 if (asprintf(&x, "INVOCATION_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(u->invocation_id)) < 0)
1827                         return -ENOMEM;
1828
1829                 our_env[n_env++] = x;
1830         }
1831
1832         if (exec_context_needs_term(c)) {
1833                 const char *tty_path, *term = NULL;
1834
1835                 tty_path = exec_context_tty_path(c);
1836
1837                 /* If we are forked off PID 1 and we are supposed to operate on /dev/console, then let's try to inherit
1838                  * the $TERM set for PID 1. This is useful for containers so that the $TERM the container manager
1839                  * passes to PID 1 ends up all the way in the console login shown. */
1840
1841                 if (path_equal(tty_path, "/dev/console") && getppid() == 1)
1842                         term = getenv("TERM");
1843                 if (!term)
1844                         term = default_term_for_tty(tty_path);
1845
1846                 x = strjoin("TERM=", term);
1847                 if (!x)
1848                         return -ENOMEM;
1849                 our_env[n_env++] = x;
1850         }
1851
1852         if (journal_stream_dev != 0 && journal_stream_ino != 0) {
1853                 if (asprintf(&x, "JOURNAL_STREAM=" DEV_FMT ":" INO_FMT, journal_stream_dev, journal_stream_ino) < 0)
1854                         return -ENOMEM;
1855
1856                 our_env[n_env++] = x;
1857         }
1858
1859         for (t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
1860                 _cleanup_free_ char *pre = NULL, *joined = NULL;
1861                 const char *n;
1862
1863                 if (!p->prefix[t])
1864                         continue;
1865
1866                 if (strv_isempty(c->directories[t].paths))
1867                         continue;
1868
1869                 n = exec_directory_env_name_to_string(t);
1870                 if (!n)
1871                         continue;
1872
1873                 pre = strjoin(p->prefix[t], "/");
1874                 if (!pre)
1875                         return -ENOMEM;
1876
1877                 joined = strv_join_prefix(c->directories[t].paths, ":", pre);
1878                 if (!joined)
1879                         return -ENOMEM;
1880
1881                 x = strjoin(n, "=", joined);
1882                 if (!x)
1883                         return -ENOMEM;
1884
1885                 our_env[n_env++] = x;
1886         }
1887
1888         our_env[n_env++] = NULL;
1889         assert(n_env <= 14 + _EXEC_DIRECTORY_TYPE_MAX);
1890
1891         *ret = TAKE_PTR(our_env);
1892
1893         return 0;
1894 }
1895
1896 static int build_pass_environment(const ExecContext *c, char ***ret) {
1897         _cleanup_strv_free_ char **pass_env = NULL;
1898         size_t n_env = 0, n_bufsize = 0;
1899         char **i;
1900
1901         STRV_FOREACH(i, c->pass_environment) {
1902                 _cleanup_free_ char *x = NULL;
1903                 char *v;
1904
1905                 v = getenv(*i);
1906                 if (!v)
1907                         continue;
1908                 x = strjoin(*i, "=", v);
1909                 if (!x)
1910                         return -ENOMEM;
1911
1912                 if (!GREEDY_REALLOC(pass_env, n_bufsize, n_env + 2))
1913                         return -ENOMEM;
1914
1915                 pass_env[n_env++] = TAKE_PTR(x);
1916                 pass_env[n_env] = NULL;
1917         }
1918
1919         *ret = TAKE_PTR(pass_env);
1920
1921         return 0;
1922 }
1923
1924 static bool exec_needs_mount_namespace(
1925                 const ExecContext *context,
1926                 const ExecParameters *params,
1927                 const ExecRuntime *runtime) {
1928
1929         assert(context);
1930         assert(params);
1931
1932         if (context->root_image)
1933                 return true;
1934
1935         if (!strv_isempty(context->read_write_paths) ||
1936             !strv_isempty(context->read_only_paths) ||
1937             !strv_isempty(context->inaccessible_paths))
1938                 return true;
1939
1940         if (context->n_bind_mounts > 0)
1941                 return true;
1942
1943         if (context->n_temporary_filesystems > 0)
1944                 return true;
1945
1946         if (!IN_SET(context->mount_flags, 0, MS_SHARED))
1947                 return true;
1948
1949         if (context->private_tmp && runtime && (runtime->tmp_dir || runtime->var_tmp_dir))
1950                 return true;
1951
1952         if (context->private_devices ||
1953             context->private_mounts ||
1954             context->protect_system != PROTECT_SYSTEM_NO ||
1955             context->protect_home != PROTECT_HOME_NO ||
1956             context->protect_kernel_tunables ||
1957             context->protect_kernel_modules ||
1958             context->protect_kernel_logs ||
1959             context->protect_control_groups)
1960                 return true;
1961
1962         if (context->root_directory) {
1963                 ExecDirectoryType t;
1964
1965                 if (context->mount_apivfs)
1966                         return true;
1967
1968                 for (t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
1969                         if (!params->prefix[t])
1970                                 continue;
1971
1972                         if (!strv_isempty(context->directories[t].paths))
1973                                 return true;
1974                 }
1975         }
1976
1977         if (context->dynamic_user &&
1978             (!strv_isempty(context->directories[EXEC_DIRECTORY_STATE].paths) ||
1979              !strv_isempty(context->directories[EXEC_DIRECTORY_CACHE].paths) ||
1980              !strv_isempty(context->directories[EXEC_DIRECTORY_LOGS].paths)))
1981                 return true;
1982
1983         return false;
1984 }
1985
1986 static int setup_private_users(uid_t uid, gid_t gid) {
1987         _cleanup_free_ char *uid_map = NULL, *gid_map = NULL;
1988         _cleanup_close_pair_ int errno_pipe[2] = { -1, -1 };
1989         _cleanup_close_ int unshare_ready_fd = -1;
1990         _cleanup_(sigkill_waitp) pid_t pid = 0;
1991         uint64_t c = 1;
1992         ssize_t n;
1993         int r;
1994
1995         /* Set up a user namespace and map root to root, the selected UID/GID to itself, and everything else to
1996          * nobody. In order to be able to write this mapping we need CAP_SETUID in the original user namespace, which
1997          * we however lack after opening the user namespace. To work around this we fork() a temporary child process,
1998          * which waits for the parent to create the new user namespace while staying in the original namespace. The
1999          * child then writes the UID mapping, under full privileges. The parent waits for the child to finish and
2000          * continues execution normally. */
2001
2002         if (uid != 0 && uid_is_valid(uid)) {
2003                 r = asprintf(&uid_map,
2004                              "0 0 1\n"                      /* Map root â†’ root */
2005                              UID_FMT " " UID_FMT " 1\n",    /* Map $UID â†’ $UID */
2006                              uid, uid);
2007                 if (r < 0)
2008                         return -ENOMEM;
2009         } else {
2010                 uid_map = strdup("0 0 1\n");            /* The case where the above is the same */
2011                 if (!uid_map)
2012                         return -ENOMEM;
2013         }
2014
2015         if (gid != 0 && gid_is_valid(gid)) {
2016                 r = asprintf(&gid_map,
2017                              "0 0 1\n"                      /* Map root â†’ root */
2018                              GID_FMT " " GID_FMT " 1\n",    /* Map $GID â†’ $GID */
2019                              gid, gid);
2020                 if (r < 0)
2021                         return -ENOMEM;
2022         } else {
2023                 gid_map = strdup("0 0 1\n");            /* The case where the above is the same */
2024                 if (!gid_map)
2025                         return -ENOMEM;
2026         }
2027
2028         /* Create a communication channel so that the parent can tell the child when it finished creating the user
2029          * namespace. */
2030         unshare_ready_fd = eventfd(0, EFD_CLOEXEC);
2031         if (unshare_ready_fd < 0)
2032                 return -errno;
2033
2034         /* Create a communication channel so that the child can tell the parent a proper error code in case it
2035          * failed. */
2036         if (pipe2(errno_pipe, O_CLOEXEC) < 0)
2037                 return -errno;
2038
2039         r = safe_fork("(sd-userns)", FORK_RESET_SIGNALS|FORK_DEATHSIG, &pid);
2040         if (r < 0)
2041                 return r;
2042         if (r == 0) {
2043                 _cleanup_close_ int fd = -1;
2044                 const char *a;
2045                 pid_t ppid;
2046
2047                 /* Child process, running in the original user namespace. Let's update the parent's UID/GID map from
2048                  * here, after the parent opened its own user namespace. */
2049
2050                 ppid = getppid();
2051                 errno_pipe[0] = safe_close(errno_pipe[0]);
2052
2053                 /* Wait until the parent unshared the user namespace */
2054                 if (read(unshare_ready_fd, &c, sizeof(c)) < 0) {
2055                         r = -errno;
2056                         goto child_fail;
2057                 }
2058
2059                 /* Disable the setgroups() system call in the child user namespace, for good. */
2060                 a = procfs_file_alloca(ppid, "setgroups");
2061                 fd = open(a, O_WRONLY|O_CLOEXEC);
2062                 if (fd < 0) {
2063                         if (errno != ENOENT) {
2064                                 r = -errno;
2065                                 goto child_fail;
2066                         }
2067
2068                         /* If the file is missing the kernel is too old, let's continue anyway. */
2069                 } else {
2070                         if (write(fd, "deny\n", 5) < 0) {
2071                                 r = -errno;
2072                                 goto child_fail;
2073                         }
2074
2075                         fd = safe_close(fd);
2076                 }
2077
2078                 /* First write the GID map */
2079                 a = procfs_file_alloca(ppid, "gid_map");
2080                 fd = open(a, O_WRONLY|O_CLOEXEC);
2081                 if (fd < 0) {
2082                         r = -errno;
2083                         goto child_fail;
2084                 }
2085                 if (write(fd, gid_map, strlen(gid_map)) < 0) {
2086                         r = -errno;
2087                         goto child_fail;
2088                 }
2089                 fd = safe_close(fd);
2090
2091                 /* The write the UID map */
2092                 a = procfs_file_alloca(ppid, "uid_map");
2093                 fd = open(a, O_WRONLY|O_CLOEXEC);
2094                 if (fd < 0) {
2095                         r = -errno;
2096                         goto child_fail;
2097                 }
2098                 if (write(fd, uid_map, strlen(uid_map)) < 0) {
2099                         r = -errno;
2100                         goto child_fail;
2101                 }
2102
2103                 _exit(EXIT_SUCCESS);
2104
2105         child_fail:
2106                 (void) write(errno_pipe[1], &r, sizeof(r));
2107                 _exit(EXIT_FAILURE);
2108         }
2109
2110         errno_pipe[1] = safe_close(errno_pipe[1]);
2111
2112         if (unshare(CLONE_NEWUSER) < 0)
2113                 return -errno;
2114
2115         /* Let the child know that the namespace is ready now */
2116         if (write(unshare_ready_fd, &c, sizeof(c)) < 0)
2117                 return -errno;
2118
2119         /* Try to read an error code from the child */
2120         n = read(errno_pipe[0], &r, sizeof(r));
2121         if (n < 0)
2122                 return -errno;
2123         if (n == sizeof(r)) { /* an error code was sent to us */
2124                 if (r < 0)
2125                         return r;
2126                 return -EIO;
2127         }
2128         if (n != 0) /* on success we should have read 0 bytes */
2129                 return -EIO;
2130
2131         r = wait_for_terminate_and_check("(sd-userns)", pid, 0);
2132         pid = 0;
2133         if (r < 0)
2134                 return r;
2135         if (r != EXIT_SUCCESS) /* If something strange happened with the child, let's consider this fatal, too */
2136                 return -EIO;
2137
2138         return 0;
2139 }
2140
2141 static bool exec_directory_is_private(const ExecContext *context, ExecDirectoryType type) {
2142         if (!context->dynamic_user)
2143                 return false;
2144
2145         if (type == EXEC_DIRECTORY_CONFIGURATION)
2146                 return false;
2147
2148         if (type == EXEC_DIRECTORY_RUNTIME && context->runtime_directory_preserve_mode == EXEC_PRESERVE_NO)
2149                 return false;
2150
2151         return true;
2152 }
2153
2154 static int setup_exec_directory(
2155                 const ExecContext *context,
2156                 const ExecParameters *params,
2157                 uid_t uid,
2158                 gid_t gid,
2159                 ExecDirectoryType type,
2160                 int *exit_status) {
2161
2162         static const int exit_status_table[_EXEC_DIRECTORY_TYPE_MAX] = {
2163                 [EXEC_DIRECTORY_RUNTIME] = EXIT_RUNTIME_DIRECTORY,
2164                 [EXEC_DIRECTORY_STATE] = EXIT_STATE_DIRECTORY,
2165                 [EXEC_DIRECTORY_CACHE] = EXIT_CACHE_DIRECTORY,
2166                 [EXEC_DIRECTORY_LOGS] = EXIT_LOGS_DIRECTORY,
2167                 [EXEC_DIRECTORY_CONFIGURATION] = EXIT_CONFIGURATION_DIRECTORY,
2168         };
2169         char **rt;
2170         int r;
2171
2172         assert(context);
2173         assert(params);
2174         assert(type >= 0 && type < _EXEC_DIRECTORY_TYPE_MAX);
2175         assert(exit_status);
2176
2177         if (!params->prefix[type])
2178                 return 0;
2179
2180         if (params->flags & EXEC_CHOWN_DIRECTORIES) {
2181                 if (!uid_is_valid(uid))
2182                         uid = 0;
2183                 if (!gid_is_valid(gid))
2184                         gid = 0;
2185         }
2186
2187         STRV_FOREACH(rt, context->directories[type].paths) {
2188                 _cleanup_free_ char *p = NULL, *pp = NULL;
2189
2190                 p = path_join(params->prefix[type], *rt);
2191                 if (!p) {
2192                         r = -ENOMEM;
2193                         goto fail;
2194                 }
2195
2196                 r = mkdir_parents_label(p, 0755);
2197                 if (r < 0)
2198                         goto fail;
2199
2200                 if (exec_directory_is_private(context, type)) {
2201                         _cleanup_free_ char *private_root = NULL;
2202
2203                         /* So, here's one extra complication when dealing with DynamicUser=1 units. In that
2204                          * case we want to avoid leaving a directory around fully accessible that is owned by
2205                          * a dynamic user whose UID is later on reused. To lock this down we use the same
2206                          * trick used by container managers to prohibit host users to get access to files of
2207                          * the same UID in containers: we place everything inside a directory that has an
2208                          * access mode of 0700 and is owned root:root, so that it acts as security boundary
2209                          * for unprivileged host code. We then use fs namespacing to make this directory
2210                          * permeable for the service itself.
2211                          *
2212                          * Specifically: for a service which wants a special directory "foo/" we first create
2213                          * a directory "private/" with access mode 0700 owned by root:root. Then we place
2214                          * "foo" inside of that directory (i.e. "private/foo/"), and make "foo" a symlink to
2215                          * "private/foo". This way, privileged host users can access "foo/" as usual, but
2216                          * unprivileged host users can't look into it. Inside of the namespace of the unit
2217                          * "private/" is replaced by a more liberally accessible tmpfs, into which the host's
2218                          * "private/foo/" is mounted under the same name, thus disabling the access boundary
2219                          * for the service and making sure it only gets access to the dirs it needs but no
2220                          * others. Tricky? Yes, absolutely, but it works!
2221                          *
2222                          * Note that we don't do this for EXEC_DIRECTORY_CONFIGURATION as that's assumed not
2223                          * to be owned by the service itself.
2224                          *
2225                          * Also, note that we don't do this for EXEC_DIRECTORY_RUNTIME as that's often used
2226                          * for sharing files or sockets with other services. */
2227
2228                         private_root = path_join(params->prefix[type], "private");
2229                         if (!private_root) {
2230                                 r = -ENOMEM;
2231                                 goto fail;
2232                         }
2233
2234                         /* First set up private root if it doesn't exist yet, with access mode 0700 and owned by root:root */
2235                         r = mkdir_safe_label(private_root, 0700, 0, 0, MKDIR_WARN_MODE);
2236                         if (r < 0)
2237                                 goto fail;
2238
2239                         pp = path_join(private_root, *rt);
2240                         if (!pp) {
2241                                 r = -ENOMEM;
2242                                 goto fail;
2243                         }
2244
2245                         /* Create all directories between the configured directory and this private root, and mark them 0755 */
2246                         r = mkdir_parents_label(pp, 0755);
2247                         if (r < 0)
2248                                 goto fail;
2249
2250                         if (is_dir(p, false) > 0 &&
2251                             (laccess(pp, F_OK) < 0 && errno == ENOENT)) {
2252
2253                                 /* Hmm, the private directory doesn't exist yet, but the normal one exists? If so, move
2254                                  * it over. Most likely the service has been upgraded from one that didn't use
2255                                  * DynamicUser=1, to one that does. */
2256
2257                                 log_info("Found pre-existing public %s= directory %s, migrating to %s.\n"
2258                                          "Apparently, service previously had DynamicUser= turned off, and has now turned it on.",
2259                                          exec_directory_type_to_string(type), p, pp);
2260
2261                                 if (rename(p, pp) < 0) {
2262                                         r = -errno;
2263                                         goto fail;
2264                                 }
2265                         } else {
2266                                 /* Otherwise, create the actual directory for the service */
2267
2268                                 r = mkdir_label(pp, context->directories[type].mode);
2269                                 if (r < 0 && r != -EEXIST)
2270                                         goto fail;
2271                         }
2272
2273                         /* And link it up from the original place */
2274                         r = symlink_idempotent(pp, p, true);
2275                         if (r < 0)
2276                                 goto fail;
2277
2278                 } else {
2279                         _cleanup_free_ char *target = NULL;
2280
2281                         if (type != EXEC_DIRECTORY_CONFIGURATION &&
2282                             readlink_and_make_absolute(p, &target) >= 0) {
2283                                 _cleanup_free_ char *q = NULL;
2284
2285                                 /* This already exists and is a symlink? Interesting. Maybe it's one created
2286                                  * by DynamicUser=1 (see above)?
2287                                  *
2288                                  * We do this for all directory types except for ConfigurationDirectory=,
2289                                  * since they all support the private/ symlink logic at least in some
2290                                  * configurations, see above. */
2291
2292                                 q = path_join(params->prefix[type], "private", *rt);
2293                                 if (!q) {
2294                                         r = -ENOMEM;
2295                                         goto fail;
2296                                 }
2297
2298                                 if (path_equal(q, target)) {
2299
2300                                         /* Hmm, apparently DynamicUser= was once turned on for this service,
2301                                          * but is no longer. Let's move the directory back up. */
2302
2303                                         log_info("Found pre-existing private %s= directory %s, migrating to %s.\n"
2304                                                  "Apparently, service previously had DynamicUser= turned on, and has now turned it off.",
2305                                                  exec_directory_type_to_string(type), q, p);
2306
2307                                         if (unlink(p) < 0) {
2308                                                 r = -errno;
2309                                                 goto fail;
2310                                         }
2311
2312                                         if (rename(q, p) < 0) {
2313                                                 r = -errno;
2314                                                 goto fail;
2315                                         }
2316                                 }
2317                         }
2318
2319                         r = mkdir_label(p, context->directories[type].mode);
2320                         if (r < 0) {
2321                                 if (r != -EEXIST)
2322                                         goto fail;
2323
2324                                 if (type == EXEC_DIRECTORY_CONFIGURATION) {
2325                                         struct stat st;
2326
2327                                         /* Don't change the owner/access mode of the configuration directory,
2328                                          * as in the common case it is not written to by a service, and shall
2329                                          * not be writable. */
2330
2331                                         if (stat(p, &st) < 0) {
2332                                                 r = -errno;
2333                                                 goto fail;
2334                                         }
2335
2336                                         /* Still complain if the access mode doesn't match */
2337                                         if (((st.st_mode ^ context->directories[type].mode) & 07777) != 0)
2338                                                 log_warning("%s \'%s\' already exists but the mode is different. "
2339                                                             "(File system: %o %sMode: %o)",
2340                                                             exec_directory_type_to_string(type), *rt,
2341                                                             st.st_mode & 07777, exec_directory_type_to_string(type), context->directories[type].mode & 07777);
2342
2343                                         continue;
2344                                 }
2345                         }
2346                 }
2347
2348                 /* Lock down the access mode (we use chmod_and_chown() to make this idempotent. We don't
2349                  * specify UID/GID here, so that path_chown_recursive() can optimize things depending on the
2350                  * current UID/GID ownership.) */
2351                 r = chmod_and_chown(pp ?: p, context->directories[type].mode, UID_INVALID, GID_INVALID);
2352                 if (r < 0)
2353                         goto fail;
2354
2355                 /* Then, change the ownership of the whole tree, if necessary. When dynamic users are used we
2356                  * drop the suid/sgid bits, since we really don't want SUID/SGID files for dynamic UID/GID
2357                  * assignments to exist.*/
2358                 r = path_chown_recursive(pp ?: p, uid, gid, context->dynamic_user ? 01777 : 07777);
2359                 if (r < 0)
2360                         goto fail;
2361         }
2362
2363         return 0;
2364
2365 fail:
2366         *exit_status = exit_status_table[type];
2367         return r;
2368 }
2369
2370 #if ENABLE_SMACK
2371 static int setup_smack(
2372                 const Manager *manager,
2373                 const ExecContext *context,
2374                 const ExecCommand *command) {
2375
2376         int r;
2377
2378         assert(context);
2379         assert(command);
2380
2381         if (context->smack_process_label) {
2382                 r = mac_smack_apply_pid(0, context->smack_process_label);
2383                 if (r < 0)
2384                         return r;
2385         } else if (manager->default_smack_process_label) {
2386                 _cleanup_free_ char *exec_label = NULL;
2387
2388                 r = mac_smack_read(command->path, SMACK_ATTR_EXEC, &exec_label);
2389                 if (r < 0 && !IN_SET(r, -ENODATA, -EOPNOTSUPP))
2390                         return r;
2391
2392                 r = mac_smack_apply_pid(0, exec_label ? : manager->default_smack_process_label);
2393                 if (r < 0)
2394                         return r;
2395         }
2396
2397         return 0;
2398 }
2399 #endif
2400
2401 static int compile_bind_mounts(
2402                 const ExecContext *context,
2403                 const ExecParameters *params,
2404                 BindMount **ret_bind_mounts,
2405                 size_t *ret_n_bind_mounts,
2406                 char ***ret_empty_directories) {
2407
2408         _cleanup_strv_free_ char **empty_directories = NULL;
2409         BindMount *bind_mounts;
2410         size_t n, h = 0, i;
2411         ExecDirectoryType t;
2412         int r;
2413
2414         assert(context);
2415         assert(params);
2416         assert(ret_bind_mounts);
2417         assert(ret_n_bind_mounts);
2418         assert(ret_empty_directories);
2419
2420         n = context->n_bind_mounts;
2421         for (t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
2422                 if (!params->prefix[t])
2423                         continue;
2424
2425                 n += strv_length(context->directories[t].paths);
2426         }
2427
2428         if (n <= 0) {
2429                 *ret_bind_mounts = NULL;
2430                 *ret_n_bind_mounts = 0;
2431                 *ret_empty_directories = NULL;
2432                 return 0;
2433         }
2434
2435         bind_mounts = new(BindMount, n);
2436         if (!bind_mounts)
2437                 return -ENOMEM;
2438
2439         for (i = 0; i < context->n_bind_mounts; i++) {
2440                 BindMount *item = context->bind_mounts + i;
2441                 char *s, *d;
2442
2443                 s = strdup(item->source);
2444                 if (!s) {
2445                         r = -ENOMEM;
2446                         goto finish;
2447                 }
2448
2449                 d = strdup(item->destination);
2450                 if (!d) {
2451                         free(s);
2452                         r = -ENOMEM;
2453                         goto finish;
2454                 }
2455
2456                 bind_mounts[h++] = (BindMount) {
2457                         .source = s,
2458                         .destination = d,
2459                         .read_only = item->read_only,
2460                         .recursive = item->recursive,
2461                         .ignore_enoent = item->ignore_enoent,
2462                 };
2463         }
2464
2465         for (t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
2466                 char **suffix;
2467
2468                 if (!params->prefix[t])
2469                         continue;
2470
2471                 if (strv_isempty(context->directories[t].paths))
2472                         continue;
2473
2474                 if (exec_directory_is_private(context, t) &&
2475                     !(context->root_directory || context->root_image)) {
2476                         char *private_root;
2477
2478                         /* So this is for a dynamic user, and we need to make sure the process can access its own
2479                          * directory. For that we overmount the usually inaccessible "private" subdirectory with a
2480                          * tmpfs that makes it accessible and is empty except for the submounts we do this for. */
2481
2482                         private_root = path_join(params->prefix[t], "private");
2483                         if (!private_root) {
2484                                 r = -ENOMEM;
2485                                 goto finish;
2486                         }
2487
2488                         r = strv_consume(&empty_directories, private_root);
2489                         if (r < 0)
2490                                 goto finish;
2491                 }
2492
2493                 STRV_FOREACH(suffix, context->directories[t].paths) {
2494                         char *s, *d;
2495
2496                         if (exec_directory_is_private(context, t))
2497                                 s = path_join(params->prefix[t], "private", *suffix);
2498                         else
2499                                 s = path_join(params->prefix[t], *suffix);
2500                         if (!s) {
2501                                 r = -ENOMEM;
2502                                 goto finish;
2503                         }
2504
2505                         if (exec_directory_is_private(context, t) &&
2506                             (context->root_directory || context->root_image))
2507                                 /* When RootDirectory= or RootImage= are set, then the symbolic link to the private
2508                                  * directory is not created on the root directory. So, let's bind-mount the directory
2509                                  * on the 'non-private' place. */
2510                                 d = path_join(params->prefix[t], *suffix);
2511                         else
2512                                 d = strdup(s);
2513                         if (!d) {
2514                                 free(s);
2515                                 r = -ENOMEM;
2516                                 goto finish;
2517                         }
2518
2519                         bind_mounts[h++] = (BindMount) {
2520                                 .source = s,
2521                                 .destination = d,
2522                                 .read_only = false,
2523                                 .nosuid = context->dynamic_user, /* don't allow suid/sgid when DynamicUser= is on */
2524                                 .recursive = true,
2525                                 .ignore_enoent = false,
2526                         };
2527                 }
2528         }
2529
2530         assert(h == n);
2531
2532         *ret_bind_mounts = bind_mounts;
2533         *ret_n_bind_mounts = n;
2534         *ret_empty_directories = TAKE_PTR(empty_directories);
2535
2536         return (int) n;
2537
2538 finish:
2539         bind_mount_free_many(bind_mounts, h);
2540         return r;
2541 }
2542
2543 static bool insist_on_sandboxing(
2544                 const ExecContext *context,
2545                 const char *root_dir,
2546                 const char *root_image,
2547                 const BindMount *bind_mounts,
2548                 size_t n_bind_mounts) {
2549
2550         size_t i;
2551
2552         assert(context);
2553         assert(n_bind_mounts == 0 || bind_mounts);
2554
2555         /* Checks whether we need to insist on fs namespacing. i.e. whether we have settings configured that
2556          * would alter the view on the file system beyond making things read-only or invisble, i.e. would
2557          * rearrange stuff in a way we cannot ignore gracefully. */
2558
2559         if (context->n_temporary_filesystems > 0)
2560                 return true;
2561
2562         if (root_dir || root_image)
2563                 return true;
2564
2565         if (context->dynamic_user)
2566                 return true;
2567
2568         /* If there are any bind mounts set that don't map back onto themselves, fs namespacing becomes
2569          * essential. */
2570         for (i = 0; i < n_bind_mounts; i++)
2571                 if (!path_equal(bind_mounts[i].source, bind_mounts[i].destination))
2572                         return true;
2573
2574         return false;
2575 }
2576
2577 static int apply_mount_namespace(
2578                 const Unit *u,
2579                 const ExecCommand *command,
2580                 const ExecContext *context,
2581                 const ExecParameters *params,
2582                 const ExecRuntime *runtime,
2583                 char **error_path) {
2584
2585         _cleanup_strv_free_ char **empty_directories = NULL;
2586         char *tmp = NULL, *var = NULL;
2587         const char *root_dir = NULL, *root_image = NULL;
2588         NamespaceInfo ns_info;
2589         bool needs_sandboxing;
2590         BindMount *bind_mounts = NULL;
2591         size_t n_bind_mounts = 0;
2592         int r;
2593
2594         assert(context);
2595
2596         /* The runtime struct only contains the parent of the private /tmp,
2597          * which is non-accessible to world users. Inside of it there's a /tmp
2598          * that is sticky, and that's the one we want to use here. */
2599
2600         if (context->private_tmp && runtime) {
2601                 if (runtime->tmp_dir)
2602                         tmp = strjoina(runtime->tmp_dir, "/tmp");
2603                 if (runtime->var_tmp_dir)
2604                         var = strjoina(runtime->var_tmp_dir, "/tmp");
2605         }
2606
2607         if (params->flags & EXEC_APPLY_CHROOT) {
2608                 root_image = context->root_image;
2609
2610                 if (!root_image)
2611                         root_dir = context->root_directory;
2612         }
2613
2614         r = compile_bind_mounts(context, params, &bind_mounts, &n_bind_mounts, &empty_directories);
2615         if (r < 0)
2616                 return r;
2617
2618         needs_sandboxing = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & EXEC_COMMAND_FULLY_PRIVILEGED);
2619         if (needs_sandboxing)
2620                 ns_info = (NamespaceInfo) {
2621                         .ignore_protect_paths = false,
2622                         .private_dev = context->private_devices,
2623                         .protect_control_groups = context->protect_control_groups,
2624                         .protect_kernel_tunables = context->protect_kernel_tunables,
2625                         .protect_kernel_modules = context->protect_kernel_modules,
2626                         .protect_kernel_logs = context->protect_kernel_logs,
2627                         .protect_hostname = context->protect_hostname,
2628                         .mount_apivfs = context->mount_apivfs,
2629                         .private_mounts = context->private_mounts,
2630                 };
2631         else if (!context->dynamic_user && root_dir)
2632                 /*
2633                  * If DynamicUser=no and RootDirectory= is set then lets pass a relaxed
2634                  * sandbox info, otherwise enforce it, don't ignore protected paths and
2635                  * fail if we are enable to apply the sandbox inside the mount namespace.
2636                  */
2637                 ns_info = (NamespaceInfo) {
2638                         .ignore_protect_paths = true,
2639                 };
2640         else
2641                 ns_info = (NamespaceInfo) {};
2642
2643         if (context->mount_flags == MS_SHARED)
2644                 log_unit_debug(u, "shared mount propagation hidden by other fs namespacing unit settings: ignoring");
2645
2646         r = setup_namespace(root_dir, root_image,
2647                             &ns_info, context->read_write_paths,
2648                             needs_sandboxing ? context->read_only_paths : NULL,
2649                             needs_sandboxing ? context->inaccessible_paths : NULL,
2650                             empty_directories,
2651                             bind_mounts,
2652                             n_bind_mounts,
2653                             context->temporary_filesystems,
2654                             context->n_temporary_filesystems,
2655                             tmp,
2656                             var,
2657                             needs_sandboxing ? context->protect_home : PROTECT_HOME_NO,
2658                             needs_sandboxing ? context->protect_system : PROTECT_SYSTEM_NO,
2659                             context->mount_flags,
2660                             DISSECT_IMAGE_DISCARD_ON_LOOP,
2661                             error_path);
2662
2663         /* If we couldn't set up the namespace this is probably due to a missing capability. setup_namespace() reports
2664          * that with a special, recognizable error ENOANO. In this case, silently proceed, but only if exclusively
2665          * sandboxing options were used, i.e. nothing such as RootDirectory= or BindMount= that would result in a
2666          * completely different execution environment. */
2667         if (r == -ENOANO) {
2668                 if (insist_on_sandboxing(
2669                                     context,
2670                                     root_dir, root_image,
2671                                     bind_mounts,
2672                                     n_bind_mounts)) {
2673                         log_unit_debug(u, "Failed to set up namespace, and refusing to continue since the selected namespacing options alter mount environment non-trivially.\n"
2674                                        "Bind mounts: %zu, temporary filesystems: %zu, root directory: %s, root image: %s, dynamic user: %s",
2675                                        n_bind_mounts, context->n_temporary_filesystems, yes_no(root_dir), yes_no(root_image), yes_no(context->dynamic_user));
2676
2677                         r = -EOPNOTSUPP;
2678                 } else {
2679                         log_unit_debug(u, "Failed to set up namespace, assuming containerized execution and ignoring.");
2680                         r = 0;
2681                 }
2682         }
2683
2684         bind_mount_free_many(bind_mounts, n_bind_mounts);
2685         return r;
2686 }
2687
2688 static int apply_working_directory(
2689                 const ExecContext *context,
2690                 const ExecParameters *params,
2691                 const char *home,
2692                 int *exit_status) {
2693
2694         const char *d, *wd;
2695
2696         assert(context);
2697         assert(exit_status);
2698
2699         if (context->working_directory_home) {
2700
2701                 if (!home) {
2702                         *exit_status = EXIT_CHDIR;
2703                         return -ENXIO;
2704                 }
2705
2706                 wd = home;
2707
2708         } else if (context->working_directory)
2709                 wd = context->working_directory;
2710         else
2711                 wd = "/";
2712
2713         if (params->flags & EXEC_APPLY_CHROOT)
2714                 d = wd;
2715         else
2716                 d = prefix_roota(context->root_directory, wd);
2717
2718         if (chdir(d) < 0 && !context->working_directory_missing_ok) {
2719                 *exit_status = EXIT_CHDIR;
2720                 return -errno;
2721         }
2722
2723         return 0;
2724 }
2725
2726 static int apply_root_directory(
2727                 const ExecContext *context,
2728                 const ExecParameters *params,
2729                 const bool needs_mount_ns,
2730                 int *exit_status) {
2731
2732         assert(context);
2733         assert(exit_status);
2734
2735         if (params->flags & EXEC_APPLY_CHROOT) {
2736                 if (!needs_mount_ns && context->root_directory)
2737                         if (chroot(context->root_directory) < 0) {
2738                                 *exit_status = EXIT_CHROOT;
2739                                 return -errno;
2740                         }
2741         }
2742
2743         return 0;
2744 }
2745
2746 static int setup_keyring(
2747                 const Unit *u,
2748                 const ExecContext *context,
2749                 const ExecParameters *p,
2750                 uid_t uid, gid_t gid) {
2751
2752         key_serial_t keyring;
2753         int r = 0;
2754         uid_t saved_uid;
2755         gid_t saved_gid;
2756
2757         assert(u);
2758         assert(context);
2759         assert(p);
2760
2761         /* Let's set up a new per-service "session" kernel keyring for each system service. This has the benefit that
2762          * each service runs with its own keyring shared among all processes of the service, but with no hook-up beyond
2763          * that scope, and in particular no link to the per-UID keyring. If we don't do this the keyring will be
2764          * automatically created on-demand and then linked to the per-UID keyring, by the kernel. The kernel's built-in
2765          * on-demand behaviour is very appropriate for login users, but probably not so much for system services, where
2766          * UIDs are not necessarily specific to a service but reused (at least in the case of UID 0). */
2767
2768         if (context->keyring_mode == EXEC_KEYRING_INHERIT)
2769                 return 0;
2770
2771         /* Acquiring a reference to the user keyring is nasty. We briefly change identity in order to get things set up
2772          * properly by the kernel. If we don't do that then we can't create it atomically, and that sucks for parallel
2773          * execution. This mimics what pam_keyinit does, too. Setting up session keyring, to be owned by the right user
2774          * & group is just as nasty as acquiring a reference to the user keyring. */
2775
2776         saved_uid = getuid();
2777         saved_gid = getgid();
2778
2779         if (gid_is_valid(gid) && gid != saved_gid) {
2780                 if (setregid(gid, -1) < 0)
2781                         return log_unit_error_errno(u, errno, "Failed to change GID for user keyring: %m");
2782         }
2783
2784         if (uid_is_valid(uid) && uid != saved_uid) {
2785                 if (setreuid(uid, -1) < 0) {
2786                         r = log_unit_error_errno(u, errno, "Failed to change UID for user keyring: %m");
2787                         goto out;
2788                 }
2789         }
2790
2791         keyring = keyctl(KEYCTL_JOIN_SESSION_KEYRING, 0, 0, 0, 0);
2792         if (keyring == -1) {
2793                 if (errno == ENOSYS)
2794                         log_unit_debug_errno(u, errno, "Kernel keyring not supported, ignoring.");
2795                 else if (IN_SET(errno, EACCES, EPERM))
2796                         log_unit_debug_errno(u, errno, "Kernel keyring access prohibited, ignoring.");
2797                 else if (errno == EDQUOT)
2798                         log_unit_debug_errno(u, errno, "Out of kernel keyrings to allocate, ignoring.");
2799                 else
2800                         r = log_unit_error_errno(u, errno, "Setting up kernel keyring failed: %m");
2801
2802                 goto out;
2803         }
2804
2805         /* When requested link the user keyring into the session keyring. */
2806         if (context->keyring_mode == EXEC_KEYRING_SHARED) {
2807
2808                 if (keyctl(KEYCTL_LINK,
2809                            KEY_SPEC_USER_KEYRING,
2810                            KEY_SPEC_SESSION_KEYRING, 0, 0) < 0) {
2811                         r = log_unit_error_errno(u, errno, "Failed to link user keyring into session keyring: %m");
2812                         goto out;
2813                 }
2814         }
2815
2816         /* Restore uid/gid back */
2817         if (uid_is_valid(uid) && uid != saved_uid) {
2818                 if (setreuid(saved_uid, -1) < 0) {
2819                         r = log_unit_error_errno(u, errno, "Failed to change UID back for user keyring: %m");
2820                         goto out;
2821                 }
2822         }
2823
2824         if (gid_is_valid(gid) && gid != saved_gid) {
2825                 if (setregid(saved_gid, -1) < 0)
2826                         return log_unit_error_errno(u, errno, "Failed to change GID back for user keyring: %m");
2827         }
2828
2829         /* Populate they keyring with the invocation ID by default, as original saved_uid. */
2830         if (!sd_id128_is_null(u->invocation_id)) {
2831                 key_serial_t key;
2832
2833                 key = add_key("user", "invocation_id", &u->invocation_id, sizeof(u->invocation_id), KEY_SPEC_SESSION_KEYRING);
2834                 if (key == -1)
2835                         log_unit_debug_errno(u, errno, "Failed to add invocation ID to keyring, ignoring: %m");
2836                 else {
2837                         if (keyctl(KEYCTL_SETPERM, key,
2838                                    KEY_POS_VIEW|KEY_POS_READ|KEY_POS_SEARCH|
2839                                    KEY_USR_VIEW|KEY_USR_READ|KEY_USR_SEARCH, 0, 0) < 0)
2840                                 r = log_unit_error_errno(u, errno, "Failed to restrict invocation ID permission: %m");
2841                 }
2842         }
2843
2844 out:
2845         /* Revert back uid & gid for the the last time, and exit */
2846         /* no extra logging, as only the first already reported error matters */
2847         if (getuid() != saved_uid)
2848                 (void) setreuid(saved_uid, -1);
2849
2850         if (getgid() != saved_gid)
2851                 (void) setregid(saved_gid, -1);
2852
2853         return r;
2854 }
2855
2856 static void append_socket_pair(int *array, size_t *n, const int pair[static 2]) {
2857         assert(array);
2858         assert(n);
2859         assert(pair);
2860
2861         if (pair[0] >= 0)
2862                 array[(*n)++] = pair[0];
2863         if (pair[1] >= 0)
2864                 array[(*n)++] = pair[1];
2865 }
2866
2867 static int close_remaining_fds(
2868                 const ExecParameters *params,
2869                 const ExecRuntime *runtime,
2870                 const DynamicCreds *dcreds,
2871                 int user_lookup_fd,
2872                 int socket_fd,
2873                 int exec_fd,
2874                 int *fds, size_t n_fds) {
2875
2876         size_t n_dont_close = 0;
2877         int dont_close[n_fds + 12];
2878
2879         assert(params);
2880
2881         if (params->stdin_fd >= 0)
2882                 dont_close[n_dont_close++] = params->stdin_fd;
2883         if (params->stdout_fd >= 0)
2884                 dont_close[n_dont_close++] = params->stdout_fd;
2885         if (params->stderr_fd >= 0)
2886                 dont_close[n_dont_close++] = params->stderr_fd;
2887
2888         if (socket_fd >= 0)
2889                 dont_close[n_dont_close++] = socket_fd;
2890         if (exec_fd >= 0)
2891                 dont_close[n_dont_close++] = exec_fd;
2892         if (n_fds > 0) {
2893                 memcpy(dont_close + n_dont_close, fds, sizeof(int) * n_fds);
2894                 n_dont_close += n_fds;
2895         }
2896
2897         if (runtime)
2898                 append_socket_pair(dont_close, &n_dont_close, runtime->netns_storage_socket);
2899
2900         if (dcreds) {
2901                 if (dcreds->user)
2902                         append_socket_pair(dont_close, &n_dont_close, dcreds->user->storage_socket);
2903                 if (dcreds->group)
2904                         append_socket_pair(dont_close, &n_dont_close, dcreds->group->storage_socket);
2905         }
2906
2907         if (user_lookup_fd >= 0)
2908                 dont_close[n_dont_close++] = user_lookup_fd;
2909
2910         return close_all_fds(dont_close, n_dont_close);
2911 }
2912
2913 static int send_user_lookup(
2914                 Unit *unit,
2915                 int user_lookup_fd,
2916                 uid_t uid,
2917                 gid_t gid) {
2918
2919         assert(unit);
2920
2921         /* Send the resolved UID/GID to PID 1 after we learnt it. We send a single datagram, containing the UID/GID
2922          * data as well as the unit name. Note that we suppress sending this if no user/group to resolve was
2923          * specified. */
2924
2925         if (user_lookup_fd < 0)
2926                 return 0;
2927
2928         if (!uid_is_valid(uid) && !gid_is_valid(gid))
2929                 return 0;
2930
2931         if (writev(user_lookup_fd,
2932                (struct iovec[]) {
2933                            IOVEC_INIT(&uid, sizeof(uid)),
2934                            IOVEC_INIT(&gid, sizeof(gid)),
2935                            IOVEC_INIT_STRING(unit->id) }, 3) < 0)
2936                 return -errno;
2937
2938         return 0;
2939 }
2940
2941 static int acquire_home(const ExecContext *c, uid_t uid, const char** home, char **buf) {
2942         int r;
2943
2944         assert(c);
2945         assert(home);
2946         assert(buf);
2947
2948         /* If WorkingDirectory=~ is set, try to acquire a usable home directory. */
2949
2950         if (*home)
2951                 return 0;
2952
2953         if (!c->working_directory_home)
2954                 return 0;
2955
2956         r = get_home_dir(buf);
2957         if (r < 0)
2958                 return r;
2959
2960         *home = *buf;
2961         return 1;
2962 }
2963
2964 static int compile_suggested_paths(const ExecContext *c, const ExecParameters *p, char ***ret) {
2965         _cleanup_strv_free_ char ** list = NULL;
2966         ExecDirectoryType t;
2967         int r;
2968
2969         assert(c);
2970         assert(p);
2971         assert(ret);
2972
2973         assert(c->dynamic_user);
2974
2975         /* Compile a list of paths that it might make sense to read the owning UID from to use as initial candidate for
2976          * dynamic UID allocation, in order to save us from doing costly recursive chown()s of the special
2977          * directories. */
2978
2979         for (t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
2980                 char **i;
2981
2982                 if (t == EXEC_DIRECTORY_CONFIGURATION)
2983                         continue;
2984
2985                 if (!p->prefix[t])
2986                         continue;
2987
2988                 STRV_FOREACH(i, c->directories[t].paths) {
2989                         char *e;
2990
2991                         if (exec_directory_is_private(c, t))
2992                                 e = path_join(p->prefix[t], "private", *i);
2993                         else
2994                                 e = path_join(p->prefix[t], *i);
2995                         if (!e)
2996                                 return -ENOMEM;
2997
2998                         r = strv_consume(&list, e);
2999                         if (r < 0)
3000                                 return r;
3001                 }
3002         }
3003
3004         *ret = TAKE_PTR(list);
3005
3006         return 0;
3007 }
3008
3009 static char *exec_command_line(char **argv);
3010
3011 static int exec_parameters_get_cgroup_path(const ExecParameters *params, char **ret) {
3012         bool using_subcgroup;
3013         char *p;
3014
3015         assert(params);
3016         assert(ret);
3017
3018         if (!params->cgroup_path)
3019                 return -EINVAL;
3020
3021         /* If we are called for a unit where cgroup delegation is on, and the payload created its own populated
3022          * subcgroup (which we expect it to do, after all it asked for delegation), then we cannot place the control
3023          * processes started after the main unit's process in the unit's main cgroup because it is now an inner one,
3024          * and inner cgroups may not contain processes. Hence, if delegation is on, and this is a control process,
3025          * let's use ".control" as subcgroup instead. Note that we do so only for ExecStartPost=, ExecReload=,
3026          * ExecStop=, ExecStopPost=, i.e. for the commands where the main process is already forked. For ExecStartPre=
3027          * this is not necessary, the cgroup is still empty. We distinguish these cases with the EXEC_CONTROL_CGROUP
3028          * flag, which is only passed for the former statements, not for the latter. */
3029
3030         using_subcgroup = FLAGS_SET(params->flags, EXEC_CONTROL_CGROUP|EXEC_CGROUP_DELEGATE|EXEC_IS_CONTROL);
3031         if (using_subcgroup)
3032                 p = path_join(params->cgroup_path, ".control");
3033         else
3034                 p = strdup(params->cgroup_path);
3035         if (!p)
3036                 return -ENOMEM;
3037
3038         *ret = p;
3039         return using_subcgroup;
3040 }
3041
3042 static int exec_child(
3043                 Unit *unit,
3044                 const ExecCommand *command,
3045                 const ExecContext *context,
3046                 const ExecParameters *params,
3047                 ExecRuntime *runtime,
3048                 DynamicCreds *dcreds,
3049                 int socket_fd,
3050                 const int named_iofds[static 3],
3051                 int *fds,
3052                 size_t n_socket_fds,
3053                 size_t n_storage_fds,
3054                 char **files_env,
3055                 int user_lookup_fd,
3056                 int *exit_status) {
3057
3058         _cleanup_strv_free_ char **our_env = NULL, **pass_env = NULL, **accum_env = NULL, **replaced_argv = NULL;
3059         int *fds_with_exec_fd, n_fds_with_exec_fd, r, ngids = 0, exec_fd = -1;
3060         _cleanup_free_ gid_t *supplementary_gids = NULL;
3061         const char *username = NULL, *groupname = NULL;
3062         _cleanup_free_ char *home_buffer = NULL;
3063         const char *home = NULL, *shell = NULL;
3064         char **final_argv = NULL;
3065         dev_t journal_stream_dev = 0;
3066         ino_t journal_stream_ino = 0;
3067         bool needs_sandboxing,          /* Do we need to set up full sandboxing? (i.e. all namespacing, all MAC stuff, caps, yadda yadda */
3068                 needs_setuid,           /* Do we need to do the actual setresuid()/setresgid() calls? */
3069                 needs_mount_namespace,  /* Do we need to set up a mount namespace for this kernel? */
3070                 needs_ambient_hack;     /* Do we need to apply the ambient capabilities hack? */
3071 #if HAVE_SELINUX
3072         _cleanup_free_ char *mac_selinux_context_net = NULL;
3073         bool use_selinux = false;
3074 #endif
3075 #if ENABLE_SMACK
3076         bool use_smack = false;
3077 #endif
3078 #if HAVE_APPARMOR
3079         bool use_apparmor = false;
3080 #endif
3081         uid_t uid = UID_INVALID;
3082         gid_t gid = GID_INVALID;
3083         size_t n_fds;
3084         ExecDirectoryType dt;
3085         int secure_bits;
3086
3087         assert(unit);
3088         assert(command);
3089         assert(context);
3090         assert(params);
3091         assert(exit_status);
3092
3093         rename_process_from_path(command->path);
3094
3095         /* We reset exactly these signals, since they are the
3096          * only ones we set to SIG_IGN in the main daemon. All
3097          * others we leave untouched because we set them to
3098          * SIG_DFL or a valid handler initially, both of which
3099          * will be demoted to SIG_DFL. */
3100         (void) default_signals(SIGNALS_CRASH_HANDLER,
3101                                SIGNALS_IGNORE, -1);
3102
3103         if (context->ignore_sigpipe)
3104                 (void) ignore_signals(SIGPIPE, -1);
3105
3106         r = reset_signal_mask();
3107         if (r < 0) {
3108                 *exit_status = EXIT_SIGNAL_MASK;
3109                 return log_unit_error_errno(unit, r, "Failed to set process signal mask: %m");
3110         }
3111
3112         if (params->idle_pipe)
3113                 do_idle_pipe_dance(params->idle_pipe);
3114
3115         /* Close fds we don't need very early to make sure we don't block init reexecution because it cannot bind its
3116          * sockets. Among the fds we close are the logging fds, and we want to keep them closed, so that we don't have
3117          * any fds open we don't really want open during the transition. In order to make logging work, we switch the
3118          * log subsystem into open_when_needed mode, so that it reopens the logs on every single log call. */
3119
3120         log_forget_fds();
3121         log_set_open_when_needed(true);
3122
3123         /* In case anything used libc syslog(), close this here, too */
3124         closelog();
3125
3126         n_fds = n_socket_fds + n_storage_fds;
3127         r = close_remaining_fds(params, runtime, dcreds, user_lookup_fd, socket_fd, params->exec_fd, fds, n_fds);
3128         if (r < 0) {
3129                 *exit_status = EXIT_FDS;
3130                 return log_unit_error_errno(unit, r, "Failed to close unwanted file descriptors: %m");
3131         }
3132
3133         if (!context->same_pgrp)
3134                 if (setsid() < 0) {
3135                         *exit_status = EXIT_SETSID;
3136                         return log_unit_error_errno(unit, errno, "Failed to create new process session: %m");
3137                 }
3138
3139         exec_context_tty_reset(context, params);
3140
3141         if (unit_shall_confirm_spawn(unit)) {
3142                 const char *vc = params->confirm_spawn;
3143                 _cleanup_free_ char *cmdline = NULL;
3144
3145                 cmdline = exec_command_line(command->argv);
3146                 if (!cmdline) {
3147                         *exit_status = EXIT_MEMORY;
3148                         return log_oom();
3149                 }
3150
3151                 r = ask_for_confirmation(vc, unit, cmdline);
3152                 if (r != CONFIRM_EXECUTE) {
3153                         if (r == CONFIRM_PRETEND_SUCCESS) {
3154                                 *exit_status = EXIT_SUCCESS;
3155                                 return 0;
3156                         }
3157                         *exit_status = EXIT_CONFIRM;
3158                         log_unit_error(unit, "Execution cancelled by the user");
3159                         return -ECANCELED;
3160                 }
3161         }
3162
3163         /* We are about to invoke NSS and PAM modules. Let's tell them what we are doing here, maybe they care. This is
3164          * used by nss-resolve to disable itself when we are about to start systemd-resolved, to avoid deadlocks. Note
3165          * that these env vars do not survive the execve(), which means they really only apply to the PAM and NSS
3166          * invocations themselves. Also note that while we'll only invoke NSS modules involved in user management they
3167          * might internally call into other NSS modules that are involved in hostname resolution, we never know. */
3168         if (setenv("SYSTEMD_ACTIVATION_UNIT", unit->id, true) != 0 ||
3169             setenv("SYSTEMD_ACTIVATION_SCOPE", MANAGER_IS_SYSTEM(unit->manager) ? "system" : "user", true) != 0) {
3170                 *exit_status = EXIT_MEMORY;
3171                 return log_unit_error_errno(unit, errno, "Failed to update environment: %m");
3172         }
3173
3174         if (context->dynamic_user && dcreds) {
3175                 _cleanup_strv_free_ char **suggested_paths = NULL;
3176
3177                 /* On top of that, make sure we bypass our own NSS module nss-systemd comprehensively for any NSS
3178                  * checks, if DynamicUser=1 is used, as we shouldn't create a feedback loop with ourselves here.*/
3179                 if (putenv((char*) "SYSTEMD_NSS_DYNAMIC_BYPASS=1") != 0) {
3180                         *exit_status = EXIT_USER;
3181                         return log_unit_error_errno(unit, errno, "Failed to update environment: %m");
3182                 }
3183
3184                 r = compile_suggested_paths(context, params, &suggested_paths);
3185                 if (r < 0) {
3186                         *exit_status = EXIT_MEMORY;
3187                         return log_oom();
3188                 }
3189
3190                 r = dynamic_creds_realize(dcreds, suggested_paths, &uid, &gid);
3191                 if (r < 0) {
3192                         *exit_status = EXIT_USER;
3193                         if (r == -EILSEQ) {
3194                                 log_unit_error(unit, "Failed to update dynamic user credentials: User or group with specified name already exists.");
3195                                 return -EOPNOTSUPP;
3196                         }
3197                         return log_unit_error_errno(unit, r, "Failed to update dynamic user credentials: %m");
3198                 }
3199
3200                 if (!uid_is_valid(uid)) {
3201                         *exit_status = EXIT_USER;
3202                         log_unit_error(unit, "UID validation failed for \""UID_FMT"\"", uid);
3203                         return -ESRCH;
3204                 }
3205
3206                 if (!gid_is_valid(gid)) {
3207                         *exit_status = EXIT_USER;
3208                         log_unit_error(unit, "GID validation failed for \""GID_FMT"\"", gid);
3209                         return -ESRCH;
3210                 }
3211
3212                 if (dcreds->user)
3213                         username = dcreds->user->name;
3214
3215         } else {
3216                 r = get_fixed_user(context, &username, &uid, &gid, &home, &shell);
3217                 if (r < 0) {
3218                         *exit_status = EXIT_USER;
3219                         return log_unit_error_errno(unit, r, "Failed to determine user credentials: %m");
3220                 }
3221
3222                 r = get_fixed_group(context, &groupname, &gid);
3223                 if (r < 0) {
3224                         *exit_status = EXIT_GROUP;
3225                         return log_unit_error_errno(unit, r, "Failed to determine group credentials: %m");
3226                 }
3227         }
3228
3229         /* Initialize user supplementary groups and get SupplementaryGroups= ones */
3230         r = get_supplementary_groups(context, username, groupname, gid,
3231                                      &supplementary_gids, &ngids);
3232         if (r < 0) {
3233                 *exit_status = EXIT_GROUP;
3234                 return log_unit_error_errno(unit, r, "Failed to determine supplementary groups: %m");
3235         }
3236
3237         r = send_user_lookup(unit, user_lookup_fd, uid, gid);
3238         if (r < 0) {
3239                 *exit_status = EXIT_USER;
3240                 return log_unit_error_errno(unit, r, "Failed to send user credentials to PID1: %m");
3241         }
3242
3243         user_lookup_fd = safe_close(user_lookup_fd);
3244
3245         r = acquire_home(context, uid, &home, &home_buffer);
3246         if (r < 0) {
3247                 *exit_status = EXIT_CHDIR;
3248                 return log_unit_error_errno(unit, r, "Failed to determine $HOME for user: %m");
3249         }
3250
3251         /* If a socket is connected to STDIN/STDOUT/STDERR, we
3252          * must sure to drop O_NONBLOCK */
3253         if (socket_fd >= 0)
3254                 (void) fd_nonblock(socket_fd, false);
3255
3256         /* Journald will try to look-up our cgroup in order to populate _SYSTEMD_CGROUP and _SYSTEMD_UNIT fields.
3257          * Hence we need to migrate to the target cgroup from init.scope before connecting to journald */
3258         if (params->cgroup_path) {
3259                 _cleanup_free_ char *p = NULL;
3260
3261                 r = exec_parameters_get_cgroup_path(params, &p);
3262                 if (r < 0) {
3263                         *exit_status = EXIT_CGROUP;
3264                         return log_unit_error_errno(unit, r, "Failed to acquire cgroup path: %m");
3265                 }
3266
3267                 r = cg_attach_everywhere(params->cgroup_supported, p, 0, NULL, NULL);
3268                 if (r < 0) {
3269                         *exit_status = EXIT_CGROUP;
3270                         return log_unit_error_errno(unit, r, "Failed to attach to cgroup %s: %m", p);
3271                 }
3272         }
3273
3274         if (context->network_namespace_path && runtime && runtime->netns_storage_socket[0] >= 0) {
3275                 r = open_netns_path(runtime->netns_storage_socket, context->network_namespace_path);
3276                 if (r < 0) {
3277                         *exit_status = EXIT_NETWORK;
3278                         return log_unit_error_errno(unit, r, "Failed to open network namespace path %s: %m", context->network_namespace_path);
3279                 }
3280         }
3281
3282         r = setup_input(context, params, socket_fd, named_iofds);
3283         if (r < 0) {
3284                 *exit_status = EXIT_STDIN;
3285                 return log_unit_error_errno(unit, r, "Failed to set up standard input: %m");
3286         }
3287
3288         r = setup_output(unit, context, params, STDOUT_FILENO, socket_fd, named_iofds, basename(command->path), uid, gid, &journal_stream_dev, &journal_stream_ino);
3289         if (r < 0) {
3290                 *exit_status = EXIT_STDOUT;
3291                 return log_unit_error_errno(unit, r, "Failed to set up standard output: %m");
3292         }
3293
3294         r = setup_output(unit, context, params, STDERR_FILENO, socket_fd, named_iofds, basename(command->path), uid, gid, &journal_stream_dev, &journal_stream_ino);
3295         if (r < 0) {
3296                 *exit_status = EXIT_STDERR;
3297                 return log_unit_error_errno(unit, r, "Failed to set up standard error output: %m");
3298         }
3299
3300         if (context->oom_score_adjust_set) {
3301                 /* When we can't make this change due to EPERM, then let's silently skip over it. User namespaces
3302                  * prohibit write access to this file, and we shouldn't trip up over that. */
3303                 r = set_oom_score_adjust(context->oom_score_adjust);
3304                 if (IN_SET(r, -EPERM, -EACCES))
3305                         log_unit_debug_errno(unit, r, "Failed to adjust OOM setting, assuming containerized execution, ignoring: %m");
3306                 else if (r < 0) {
3307                         *exit_status = EXIT_OOM_ADJUST;
3308                         return log_unit_error_errno(unit, r, "Failed to adjust OOM setting: %m");
3309                 }
3310         }
3311
3312         if (context->nice_set)
3313                 if (setpriority(PRIO_PROCESS, 0, context->nice) < 0) {
3314                         *exit_status = EXIT_NICE;
3315                         return log_unit_error_errno(unit, errno, "Failed to set up process scheduling priority (nice level): %m");
3316                 }
3317
3318         if (context->cpu_sched_set) {
3319                 struct sched_param param = {
3320                         .sched_priority = context->cpu_sched_priority,
3321                 };
3322
3323                 r = sched_setscheduler(0,
3324                                        context->cpu_sched_policy |
3325                                        (context->cpu_sched_reset_on_fork ?
3326                                         SCHED_RESET_ON_FORK : 0),
3327                                        &param);
3328                 if (r < 0) {
3329                         *exit_status = EXIT_SETSCHEDULER;
3330                         return log_unit_error_errno(unit, errno, "Failed to set up CPU scheduling: %m");
3331                 }
3332         }
3333
3334         if (context->cpu_set.set)
3335                 if (sched_setaffinity(0, context->cpu_set.allocated, context->cpu_set.set) < 0) {
3336                         *exit_status = EXIT_CPUAFFINITY;
3337                         return log_unit_error_errno(unit, errno, "Failed to set up CPU affinity: %m");
3338                 }
3339
3340         if (mpol_is_valid(numa_policy_get_type(&context->numa_policy))) {
3341                 r = apply_numa_policy(&context->numa_policy);
3342                 if (r == -EOPNOTSUPP)
3343                         log_unit_debug_errno(unit, r, "NUMA support not available, ignoring.");
3344                 else if (r < 0) {
3345                         *exit_status = EXIT_NUMA_POLICY;
3346                         return log_unit_error_errno(unit, r, "Failed to set NUMA memory policy: %m");
3347                 }
3348         }
3349
3350         if (context->ioprio_set)
3351                 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
3352                         *exit_status = EXIT_IOPRIO;
3353                         return log_unit_error_errno(unit, errno, "Failed to set up IO scheduling priority: %m");
3354                 }
3355
3356         if (context->timer_slack_nsec != NSEC_INFINITY)
3357                 if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
3358                         *exit_status = EXIT_TIMERSLACK;
3359                         return log_unit_error_errno(unit, errno, "Failed to set up timer slack: %m");
3360                 }
3361
3362         if (context->personality != PERSONALITY_INVALID) {
3363                 r = safe_personality(context->personality);
3364                 if (r < 0) {
3365                         *exit_status = EXIT_PERSONALITY;
3366                         return log_unit_error_errno(unit, r, "Failed to set up execution domain (personality): %m");
3367                 }
3368         }
3369
3370         if (context->utmp_id)
3371                 utmp_put_init_process(context->utmp_id, getpid_cached(), getsid(0),
3372                                       context->tty_path,
3373                                       context->utmp_mode == EXEC_UTMP_INIT  ? INIT_PROCESS :
3374                                       context->utmp_mode == EXEC_UTMP_LOGIN ? LOGIN_PROCESS :
3375                                       USER_PROCESS,
3376                                       username);
3377
3378         if (uid_is_valid(uid)) {
3379                 r = chown_terminal(STDIN_FILENO, uid);
3380                 if (r < 0) {
3381                         *exit_status = EXIT_STDIN;
3382                         return log_unit_error_errno(unit, r, "Failed to change ownership of terminal: %m");
3383                 }
3384         }
3385
3386         /* If delegation is enabled we'll pass ownership of the cgroup to the user of the new process. On cgroup v1
3387          * this is only about systemd's own hierarchy, i.e. not the controller hierarchies, simply because that's not
3388          * safe. On cgroup v2 there's only one hierarchy anyway, and delegation is safe there, hence in that case only
3389          * touch a single hierarchy too. */
3390         if (params->cgroup_path && context->user && (params->flags & EXEC_CGROUP_DELEGATE)) {
3391                 r = cg_set_access(SYSTEMD_CGROUP_CONTROLLER, params->cgroup_path, uid, gid);
3392                 if (r < 0) {
3393                         *exit_status = EXIT_CGROUP;
3394                         return log_unit_error_errno(unit, r, "Failed to adjust control group access: %m");
3395                 }
3396         }
3397
3398         for (dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
3399                 r = setup_exec_directory(context, params, uid, gid, dt, exit_status);
3400                 if (r < 0)
3401                         return log_unit_error_errno(unit, r, "Failed to set up special execution directory in %s: %m", params->prefix[dt]);
3402         }
3403
3404         r = build_environment(
3405                         unit,
3406                         context,
3407                         params,
3408                         n_fds,
3409                         home,
3410                         username,
3411                         shell,
3412                         journal_stream_dev,
3413                         journal_stream_ino,
3414                         &our_env);
3415         if (r < 0) {
3416                 *exit_status = EXIT_MEMORY;
3417                 return log_oom();
3418         }
3419
3420         r = build_pass_environment(context, &pass_env);
3421         if (r < 0) {
3422                 *exit_status = EXIT_MEMORY;
3423                 return log_oom();
3424         }
3425
3426         accum_env = strv_env_merge(5,
3427                                    params->environment,
3428                                    our_env,
3429                                    pass_env,
3430                                    context->environment,
3431                                    files_env,
3432                                    NULL);
3433         if (!accum_env) {
3434                 *exit_status = EXIT_MEMORY;
3435                 return log_oom();
3436         }
3437         accum_env = strv_env_clean(accum_env);
3438
3439         (void) umask(context->umask);
3440
3441         r = setup_keyring(unit, context, params, uid, gid);
3442         if (r < 0) {
3443                 *exit_status = EXIT_KEYRING;
3444                 return log_unit_error_errno(unit, r, "Failed to set up kernel keyring: %m");
3445         }
3446
3447         /* We need sandboxing if the caller asked us to apply it and the command isn't explicitly excepted from it */
3448         needs_sandboxing = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & EXEC_COMMAND_FULLY_PRIVILEGED);
3449
3450         /* We need the ambient capability hack, if the caller asked us to apply it and the command is marked for it, and the kernel doesn't actually support ambient caps */
3451         needs_ambient_hack = (params->flags & EXEC_APPLY_SANDBOXING) && (command->flags & EXEC_COMMAND_AMBIENT_MAGIC) && !ambient_capabilities_supported();
3452
3453         /* We need setresuid() if the caller asked us to apply sandboxing and the command isn't explicitly excepted from either whole sandboxing or just setresuid() itself, and the ambient hack is not desired */
3454         if (needs_ambient_hack)
3455                 needs_setuid = false;
3456         else
3457                 needs_setuid = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & (EXEC_COMMAND_FULLY_PRIVILEGED|EXEC_COMMAND_NO_SETUID));
3458
3459         if (needs_sandboxing) {
3460                 /* MAC enablement checks need to be done before a new mount ns is created, as they rely on /sys being
3461                  * present. The actual MAC context application will happen later, as late as possible, to avoid
3462                  * impacting our own code paths. */
3463
3464 #if HAVE_SELINUX
3465                 use_selinux = mac_selinux_use();
3466 #endif
3467 #if ENABLE_SMACK
3468                 use_smack = mac_smack_use();
3469 #endif
3470 #if HAVE_APPARMOR
3471                 use_apparmor = mac_apparmor_use();
3472 #endif
3473         }
3474
3475         if (needs_sandboxing) {
3476                 int which_failed;
3477
3478                 /* Let's set the resource limits before we call into PAM, so that pam_limits wins over what
3479                  * is set here. (See below.) */
3480
3481                 r = setrlimit_closest_all((const struct rlimit* const *) context->rlimit, &which_failed);
3482                 if (r < 0) {
3483                         *exit_status = EXIT_LIMITS;
3484                         return log_unit_error_errno(unit, r, "Failed to adjust resource limit RLIMIT_%s: %m", rlimit_to_string(which_failed));
3485                 }
3486         }
3487
3488         if (needs_setuid) {
3489
3490                 /* Let's call into PAM after we set up our own idea of resource limits to that pam_limits
3491                  * wins here. (See above.) */
3492
3493                 if (context->pam_name && username) {
3494                         r = setup_pam(context->pam_name, username, uid, gid, context->tty_path, &accum_env, fds, n_fds);
3495                         if (r < 0) {
3496                                 *exit_status = EXIT_PAM;
3497                                 return log_unit_error_errno(unit, r, "Failed to set up PAM session: %m");
3498                         }
3499                 }
3500         }
3501
3502         if ((context->private_network || context->network_namespace_path) && runtime && runtime->netns_storage_socket[0] >= 0) {
3503
3504                 if (ns_type_supported(NAMESPACE_NET)) {
3505                         r = setup_netns(runtime->netns_storage_socket);
3506                         if (r < 0) {
3507                                 *exit_status = EXIT_NETWORK;
3508                                 return log_unit_error_errno(unit, r, "Failed to set up network namespacing: %m");
3509                         }
3510                 } else if (context->network_namespace_path) {
3511                         *exit_status = EXIT_NETWORK;
3512                         return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EOPNOTSUPP), "NetworkNamespacePath= is not supported, refusing.");
3513                 } else
3514                         log_unit_warning(unit, "PrivateNetwork=yes is configured, but the kernel does not support network namespaces, ignoring.");
3515         }
3516
3517         needs_mount_namespace = exec_needs_mount_namespace(context, params, runtime);
3518         if (needs_mount_namespace) {
3519                 _cleanup_free_ char *error_path = NULL;
3520
3521                 r = apply_mount_namespace(unit, command, context, params, runtime, &error_path);
3522                 if (r < 0) {
3523                         *exit_status = EXIT_NAMESPACE;
3524                         return log_unit_error_errno(unit, r, "Failed to set up mount namespacing%s%s: %m",
3525                                                     error_path ? ": " : "", strempty(error_path));
3526                 }
3527         }
3528
3529         if (context->protect_hostname) {
3530                 if (ns_type_supported(NAMESPACE_UTS)) {
3531                         if (unshare(CLONE_NEWUTS) < 0) {
3532                                 if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno)) {
3533                                         *exit_status = EXIT_NAMESPACE;
3534                                         return log_unit_error_errno(unit, errno, "Failed to set up UTS namespacing: %m");
3535                                 }
3536
3537                                 log_unit_warning(unit, "ProtectHostname=yes is configured, but UTS namespace setup is prohibited (container manager?), ignoring namespace setup.");
3538                         }
3539                 } else
3540                         log_unit_warning(unit, "ProtectHostname=yes is configured, but the kernel does not support UTS namespaces, ignoring namespace setup.");
3541 #if HAVE_SECCOMP
3542                 r = seccomp_protect_hostname();
3543                 if (r < 0) {
3544                         *exit_status = EXIT_SECCOMP;
3545                         return log_unit_error_errno(unit, r, "Failed to apply hostname restrictions: %m");
3546                 }
3547 #endif
3548         }
3549
3550         /* Drop groups as early as possbile */
3551         if (needs_setuid) {
3552                 r = enforce_groups(gid, supplementary_gids, ngids);
3553                 if (r < 0) {
3554                         *exit_status = EXIT_GROUP;
3555                         return log_unit_error_errno(unit, r, "Changing group credentials failed: %m");
3556                 }
3557         }
3558
3559         if (needs_sandboxing) {
3560 #if HAVE_SELINUX
3561                 if (use_selinux && params->selinux_context_net && socket_fd >= 0) {
3562                         r = mac_selinux_get_child_mls_label(socket_fd, command->path, context->selinux_context, &mac_selinux_context_net);
3563                         if (r < 0) {
3564                                 *exit_status = EXIT_SELINUX_CONTEXT;
3565                                 return log_unit_error_errno(unit, r, "Failed to determine SELinux context: %m");
3566                         }
3567                 }
3568 #endif
3569
3570                 if (context->private_users) {
3571                         r = setup_private_users(uid, gid);
3572                         if (r < 0) {
3573                                 *exit_status = EXIT_USER;
3574                                 return log_unit_error_errno(unit, r, "Failed to set up user namespacing: %m");
3575                         }
3576                 }
3577         }
3578
3579         /* We repeat the fd closing here, to make sure that nothing is leaked from the PAM modules. Note that we are
3580          * more aggressive this time since socket_fd and the netns fds we don't need anymore. We do keep the exec_fd
3581          * however if we have it as we want to keep it open until the final execve(). */
3582
3583         if (params->exec_fd >= 0) {
3584                 exec_fd = params->exec_fd;
3585
3586                 if (exec_fd < 3 + (int) n_fds) {
3587                         int moved_fd;
3588
3589                         /* Let's move the exec fd far up, so that it's outside of the fd range we want to pass to the
3590                          * process we are about to execute. */
3591
3592                         moved_fd = fcntl(exec_fd, F_DUPFD_CLOEXEC, 3 + (int) n_fds);
3593                         if (moved_fd < 0) {
3594                                 *exit_status = EXIT_FDS;
3595                                 return log_unit_error_errno(unit, errno, "Couldn't move exec fd up: %m");
3596                         }
3597
3598                         safe_close(exec_fd);
3599                         exec_fd = moved_fd;
3600                 } else {
3601                         /* This fd should be FD_CLOEXEC already, but let's make sure. */
3602                         r = fd_cloexec(exec_fd, true);
3603                         if (r < 0) {
3604                                 *exit_status = EXIT_FDS;
3605                                 return log_unit_error_errno(unit, r, "Failed to make exec fd FD_CLOEXEC: %m");
3606                         }
3607                 }
3608
3609                 fds_with_exec_fd = newa(int, n_fds + 1);
3610                 memcpy_safe(fds_with_exec_fd, fds, n_fds * sizeof(int));
3611                 fds_with_exec_fd[n_fds] = exec_fd;
3612                 n_fds_with_exec_fd = n_fds + 1;
3613         } else {
3614                 fds_with_exec_fd = fds;
3615                 n_fds_with_exec_fd = n_fds;
3616         }
3617
3618         r = close_all_fds(fds_with_exec_fd, n_fds_with_exec_fd);
3619         if (r >= 0)
3620                 r = shift_fds(fds, n_fds);
3621         if (r >= 0)
3622                 r = flags_fds(fds, n_socket_fds, n_storage_fds, context->non_blocking);
3623         if (r < 0) {
3624                 *exit_status = EXIT_FDS;
3625                 return log_unit_error_errno(unit, r, "Failed to adjust passed file descriptors: %m");
3626         }
3627
3628         /* At this point, the fds we want to pass to the program are all ready and set up, with O_CLOEXEC turned off
3629          * and at the right fd numbers. The are no other fds open, with one exception: the exec_fd if it is defined,
3630          * and it has O_CLOEXEC set, after all we want it to be closed by the execve(), so that our parent knows we
3631          * came this far. */
3632
3633         secure_bits = context->secure_bits;
3634
3635         if (needs_sandboxing) {
3636                 uint64_t bset;
3637
3638                 /* Set the RTPRIO resource limit to 0, but only if nothing else was explicitly
3639                  * requested. (Note this is placed after the general resource limit initialization, see
3640                  * above, in order to take precedence.) */
3641                 if (context->restrict_realtime && !context->rlimit[RLIMIT_RTPRIO]) {
3642                         if (setrlimit(RLIMIT_RTPRIO, &RLIMIT_MAKE_CONST(0)) < 0) {
3643                                 *exit_status = EXIT_LIMITS;
3644                                 return log_unit_error_errno(unit, errno, "Failed to adjust RLIMIT_RTPRIO resource limit: %m");
3645                         }
3646                 }
3647
3648 #if ENABLE_SMACK
3649                 /* LSM Smack needs the capability CAP_MAC_ADMIN to change the current execution security context of the
3650                  * process. This is the latest place before dropping capabilities. Other MAC context are set later. */
3651                 if (use_smack) {
3652                         r = setup_smack(unit->manager, context, command);
3653                         if (r < 0) {
3654                                 *exit_status = EXIT_SMACK_PROCESS_LABEL;
3655                                 return log_unit_error_errno(unit, r, "Failed to set SMACK process label: %m");
3656                         }
3657                 }
3658 #endif
3659
3660                 bset = context->capability_bounding_set;
3661                 /* If the ambient caps hack is enabled (which means the kernel can't do them, and the user asked for
3662                  * our magic fallback), then let's add some extra caps, so that the service can drop privs of its own,
3663                  * instead of us doing that */
3664                 if (needs_ambient_hack)
3665                         bset |= (UINT64_C(1) << CAP_SETPCAP) |
3666                                 (UINT64_C(1) << CAP_SETUID) |
3667                                 (UINT64_C(1) << CAP_SETGID);
3668
3669                 if (!cap_test_all(bset)) {
3670                         r = capability_bounding_set_drop(bset, false);
3671                         if (r < 0) {
3672                                 *exit_status = EXIT_CAPABILITIES;
3673                                 return log_unit_error_errno(unit, r, "Failed to drop capabilities: %m");
3674                         }
3675                 }
3676
3677                 /* This is done before enforce_user, but ambient set
3678                  * does not survive over setresuid() if keep_caps is not set. */
3679                 if (!needs_ambient_hack &&
3680                     context->capability_ambient_set != 0) {
3681                         r = capability_ambient_set_apply(context->capability_ambient_set, true);
3682                         if (r < 0) {
3683                                 *exit_status = EXIT_CAPABILITIES;
3684                                 return log_unit_error_errno(unit, r, "Failed to apply ambient capabilities (before UID change): %m");
3685                         }
3686
3687                         if (context->capabilities) {
3688
3689                                 /* The capabilities in ambient set need to be also in the inherited
3690                                  * set. If they aren't, trying to get them will fail. Add the ambient
3691                                  * set inherited capabilities to the capability set in the context.
3692                                  * This is needed because if capabilities are set (using "Capabilities="
3693                                  * keyword), they will override whatever we set now. */
3694
3695                                 r = capability_update_inherited_set(context->capabilities, context->capability_ambient_set);
3696                                 if (r < 0) {
3697                                         *exit_status = EXIT_CAPABILITIES;
3698                                         return r;
3699                                 }
3700                         }
3701
3702                 }
3703         }
3704
3705         /* chroot to root directory first, before we lose the ability to chroot */
3706         r = apply_root_directory(context, params, needs_mount_namespace, exit_status);
3707         if (r < 0)
3708                 return log_unit_error_errno(unit, r, "Chrooting to the requested root directory failed: %m");
3709
3710         if (needs_setuid) {
3711                 if (uid_is_valid(uid)) {
3712                         r = enforce_user(context, uid);
3713                         if (r < 0) {
3714                                 *exit_status = EXIT_USER;
3715                                 return log_unit_error_errno(unit, r, "Failed to change UID to " UID_FMT ": %m", uid);
3716                         }
3717
3718                         if (!needs_ambient_hack &&
3719                             context->capability_ambient_set != 0) {
3720
3721                                 /* Fix the ambient capabilities after user change. */
3722                                 r = capability_ambient_set_apply(context->capability_ambient_set, false);
3723                                 if (r < 0) {
3724                                         *exit_status = EXIT_CAPABILITIES;
3725                                         return log_unit_error_errno(unit, r, "Failed to apply ambient capabilities (after UID change): %m");
3726                                 }
3727
3728                                 /* If we were asked to change user and ambient capabilities
3729                                  * were requested, we had to add keep-caps to the securebits
3730                                  * so that we would maintain the inherited capability set
3731                                  * through the setresuid(). Make sure that the bit is added
3732                                  * also to the context secure_bits so that we don't try to
3733                                  * drop the bit away next. */
3734
3735                                 secure_bits |= 1<<SECURE_KEEP_CAPS;
3736                         }
3737                 }
3738         }
3739
3740         /* Apply working directory here, because the working directory might be on NFS and only the user running
3741          * this service might have the correct privilege to change to the working directory */
3742         r = apply_working_directory(context, params, home, exit_status);
3743         if (r < 0)
3744                 return log_unit_error_errno(unit, r, "Changing to the requested working directory failed: %m");
3745
3746         if (needs_sandboxing) {
3747                 /* Apply other MAC contexts late, but before seccomp syscall filtering, as those should really be last to
3748                  * influence our own codepaths as little as possible. Moreover, applying MAC contexts usually requires
3749                  * syscalls that are subject to seccomp filtering, hence should probably be applied before the syscalls
3750                  * are restricted. */
3751
3752 #if HAVE_SELINUX
3753                 if (use_selinux) {
3754                         char *exec_context = mac_selinux_context_net ?: context->selinux_context;
3755
3756                         if (exec_context) {
3757                                 r = setexeccon(exec_context);
3758                                 if (r < 0) {
3759                                         *exit_status = EXIT_SELINUX_CONTEXT;
3760                                         return log_unit_error_errno(unit, r, "Failed to change SELinux context to %s: %m", exec_context);
3761                                 }
3762                         }
3763                 }
3764 #endif
3765
3766 #if HAVE_APPARMOR
3767                 if (use_apparmor && context->apparmor_profile) {
3768                         r = aa_change_onexec(context->apparmor_profile);
3769                         if (r < 0 && !context->apparmor_profile_ignore) {
3770                                 *exit_status = EXIT_APPARMOR_PROFILE;
3771                                 return log_unit_error_errno(unit, errno, "Failed to prepare AppArmor profile change to %s: %m", context->apparmor_profile);
3772                         }
3773                 }
3774 #endif
3775
3776                 /* PR_GET_SECUREBITS is not privileged, while PR_SET_SECUREBITS is. So to suppress potential EPERMs
3777                  * we'll try not to call PR_SET_SECUREBITS unless necessary. */
3778                 if (prctl(PR_GET_SECUREBITS) != secure_bits)
3779                         if (prctl(PR_SET_SECUREBITS, secure_bits) < 0) {
3780                                 *exit_status = EXIT_SECUREBITS;
3781                                 return log_unit_error_errno(unit, errno, "Failed to set process secure bits: %m");
3782                         }
3783
3784                 if (context->capabilities)
3785                         if (cap_set_proc(context->capabilities) < 0) {
3786                                 *exit_status = EXIT_CAPABILITIES;
3787                                 return -errno;
3788                         }
3789
3790                 if (context_has_no_new_privileges(context))
3791                         if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
3792                                 *exit_status = EXIT_NO_NEW_PRIVILEGES;
3793                                 return log_unit_error_errno(unit, errno, "Failed to disable new privileges: %m");
3794                         }
3795
3796 #if HAVE_SECCOMP
3797                 r = apply_address_families(unit, context);
3798                 if (r < 0) {
3799                         *exit_status = EXIT_ADDRESS_FAMILIES;
3800                         return log_unit_error_errno(unit, r, "Failed to restrict address families: %m");
3801                 }
3802
3803                 r = apply_memory_deny_write_execute(unit, context);
3804                 if (r < 0) {
3805                         *exit_status = EXIT_SECCOMP;
3806                         return log_unit_error_errno(unit, r, "Failed to disable writing to executable memory: %m");
3807                 }
3808
3809                 r = apply_restrict_realtime(unit, context);
3810                 if (r < 0) {
3811                         *exit_status = EXIT_SECCOMP;
3812                         return log_unit_error_errno(unit, r, "Failed to apply realtime restrictions: %m");
3813                 }
3814
3815                 r = apply_restrict_suid_sgid(unit, context);
3816                 if (r < 0) {
3817                         *exit_status = EXIT_SECCOMP;
3818                         return log_unit_error_errno(unit, r, "Failed to apply SUID/SGID restrictions: %m");
3819                 }
3820
3821                 r = apply_restrict_namespaces(unit, context);
3822                 if (r < 0) {
3823                         *exit_status = EXIT_SECCOMP;
3824                         return log_unit_error_errno(unit, r, "Failed to apply namespace restrictions: %m");
3825                 }
3826
3827                 r = apply_protect_sysctl(unit, context);
3828                 if (r < 0) {
3829                         *exit_status = EXIT_SECCOMP;
3830                         return log_unit_error_errno(unit, r, "Failed to apply sysctl restrictions: %m");
3831                 }
3832
3833                 r = apply_protect_kernel_modules(unit, context);
3834                 if (r < 0) {
3835                         *exit_status = EXIT_SECCOMP;
3836                         return log_unit_error_errno(unit, r, "Failed to apply module loading restrictions: %m");
3837                 }
3838
3839                 r = apply_protect_kernel_logs(unit, context);
3840                 if (r < 0) {
3841                         *exit_status = EXIT_SECCOMP;
3842                         return log_unit_error_errno(unit, r, "Failed to apply kernel log restrictions: %m");
3843                 }
3844
3845                 r = apply_private_devices(unit, context);
3846                 if (r < 0) {
3847                         *exit_status = EXIT_SECCOMP;
3848                         return log_unit_error_errno(unit, r, "Failed to set up private devices: %m");
3849                 }
3850
3851                 r = apply_syscall_archs(unit, context);
3852                 if (r < 0) {
3853                         *exit_status = EXIT_SECCOMP;
3854                         return log_unit_error_errno(unit, r, "Failed to apply syscall architecture restrictions: %m");
3855                 }
3856
3857                 r = apply_lock_personality(unit, context);
3858                 if (r < 0) {
3859                         *exit_status = EXIT_SECCOMP;
3860                         return log_unit_error_errno(unit, r, "Failed to lock personalities: %m");
3861                 }
3862
3863                 /* This really should remain the last step before the execve(), to make sure our own code is unaffected
3864                  * by the filter as little as possible. */
3865                 r = apply_syscall_filter(unit, context, needs_ambient_hack);
3866                 if (r < 0) {
3867                         *exit_status = EXIT_SECCOMP;
3868                         return log_unit_error_errno(unit, r, "Failed to apply system call filters: %m");
3869                 }
3870 #endif
3871         }
3872
3873         if (!strv_isempty(context->unset_environment)) {
3874                 char **ee = NULL;
3875
3876                 ee = strv_env_delete(accum_env, 1, context->unset_environment);
3877                 if (!ee) {
3878                         *exit_status = EXIT_MEMORY;
3879                         return log_oom();
3880                 }
3881
3882                 strv_free_and_replace(accum_env, ee);
3883         }
3884
3885         if (!FLAGS_SET(command->flags, EXEC_COMMAND_NO_ENV_EXPAND)) {
3886                 replaced_argv = replace_env_argv(command->argv, accum_env);
3887                 if (!replaced_argv) {
3888                         *exit_status = EXIT_MEMORY;
3889                         return log_oom();
3890                 }
3891                 final_argv = replaced_argv;
3892         } else
3893                 final_argv = command->argv;
3894
3895         if (DEBUG_LOGGING) {
3896                 _cleanup_free_ char *line;
3897
3898                 line = exec_command_line(final_argv);
3899                 if (line)
3900                         log_struct(LOG_DEBUG,
3901                                    "EXECUTABLE=%s", command->path,
3902                                    LOG_UNIT_MESSAGE(unit, "Executing: %s", line),
3903                                    LOG_UNIT_ID(unit),
3904                                    LOG_UNIT_INVOCATION_ID(unit));
3905         }
3906
3907         if (exec_fd >= 0) {
3908                 uint8_t hot = 1;
3909
3910                 /* We have finished with all our initializations. Let's now let the manager know that. From this point
3911                  * on, if the manager sees POLLHUP on the exec_fd, then execve() was successful. */
3912
3913                 if (write(exec_fd, &hot, sizeof(hot)) < 0) {
3914                         *exit_status = EXIT_EXEC;
3915                         return log_unit_error_errno(unit, errno, "Failed to enable exec_fd: %m");
3916                 }
3917         }
3918
3919         execve(command->path, final_argv, accum_env);
3920         r = -errno;
3921
3922         if (exec_fd >= 0) {
3923                 uint8_t hot = 0;
3924
3925                 /* The execve() failed. This means the exec_fd is still open. Which means we need to tell the manager
3926                  * that POLLHUP on it no longer means execve() succeeded. */
3927
3928                 if (write(exec_fd, &hot, sizeof(hot)) < 0) {
3929                         *exit_status = EXIT_EXEC;
3930                         return log_unit_error_errno(unit, errno, "Failed to disable exec_fd: %m");
3931                 }
3932         }
3933
3934         if (r == -ENOENT && (command->flags & EXEC_COMMAND_IGNORE_FAILURE)) {
3935                 log_struct_errno(LOG_INFO, r,
3936                                  "MESSAGE_ID=" SD_MESSAGE_SPAWN_FAILED_STR,
3937                                  LOG_UNIT_ID(unit),
3938                                  LOG_UNIT_INVOCATION_ID(unit),
3939                                  LOG_UNIT_MESSAGE(unit, "Executable %s missing, skipping: %m",
3940                                                   command->path),
3941                                  "EXECUTABLE=%s", command->path);
3942                 return 0;
3943         }
3944
3945         *exit_status = EXIT_EXEC;
3946         return log_unit_error_errno(unit, r, "Failed to execute command: %m");
3947 }
3948
3949 static int exec_context_load_environment(const Unit *unit, const ExecContext *c, char ***l);
3950 static int exec_context_named_iofds(const ExecContext *c, const ExecParameters *p, int named_iofds[static 3]);
3951
3952 int exec_spawn(Unit *unit,
3953                ExecCommand *command,
3954                const ExecContext *context,
3955                const ExecParameters *params,
3956                ExecRuntime *runtime,
3957                DynamicCreds *dcreds,
3958                pid_t *ret) {
3959
3960         int socket_fd, r, named_iofds[3] = { -1, -1, -1 }, *fds = NULL;
3961         _cleanup_free_ char *subcgroup_path = NULL;
3962         _cleanup_strv_free_ char **files_env = NULL;
3963         size_t n_storage_fds = 0, n_socket_fds = 0;
3964         _cleanup_free_ char *line = NULL;
3965         pid_t pid;
3966
3967         assert(unit);
3968         assert(command);
3969         assert(context);
3970         assert(ret);
3971         assert(params);
3972         assert(params->fds || (params->n_socket_fds + params->n_storage_fds <= 0));
3973
3974         if (context->std_input == EXEC_INPUT_SOCKET ||
3975             context->std_output == EXEC_OUTPUT_SOCKET ||
3976             context->std_error == EXEC_OUTPUT_SOCKET) {
3977
3978                 if (params->n_socket_fds > 1) {
3979                         log_unit_error(unit, "Got more than one socket.");
3980                         return -EINVAL;
3981                 }
3982
3983                 if (params->n_socket_fds == 0) {
3984                         log_unit_error(unit, "Got no socket.");
3985                         return -EINVAL;
3986                 }
3987
3988                 socket_fd = params->fds[0];
3989         } else {
3990                 socket_fd = -1;
3991                 fds = params->fds;
3992                 n_socket_fds = params->n_socket_fds;
3993                 n_storage_fds = params->n_storage_fds;
3994         }
3995
3996         r = exec_context_named_iofds(context, params, named_iofds);
3997         if (r < 0)
3998                 return log_unit_error_errno(unit, r, "Failed to load a named file descriptor: %m");
3999
4000         r = exec_context_load_environment(unit, context, &files_env);
4001         if (r < 0)
4002                 return log_unit_error_errno(unit, r, "Failed to load environment files: %m");
4003
4004         line = exec_command_line(command->argv);
4005         if (!line)
4006                 return log_oom();
4007
4008         log_struct(LOG_DEBUG,
4009                    LOG_UNIT_MESSAGE(unit, "About to execute: %s", line),
4010                    "EXECUTABLE=%s", command->path,
4011                    LOG_UNIT_ID(unit),
4012                    LOG_UNIT_INVOCATION_ID(unit));
4013
4014         if (params->cgroup_path) {
4015                 r = exec_parameters_get_cgroup_path(params, &subcgroup_path);
4016                 if (r < 0)
4017                         return log_unit_error_errno(unit, r, "Failed to acquire subcgroup path: %m");
4018                 if (r > 0) { /* We are using a child cgroup */
4019                         r = cg_create(SYSTEMD_CGROUP_CONTROLLER, subcgroup_path);
4020                         if (r < 0)
4021                                 return log_unit_error_errno(unit, r, "Failed to create control group '%s': %m", subcgroup_path);
4022                 }
4023         }
4024
4025         pid = fork();
4026         if (pid < 0)
4027                 return log_unit_error_errno(unit, errno, "Failed to fork: %m");
4028
4029         if (pid == 0) {
4030                 int exit_status = EXIT_SUCCESS;
4031
4032                 r = exec_child(unit,
4033                                command,
4034                                context,
4035                                params,
4036                                runtime,
4037                                dcreds,
4038                                socket_fd,
4039                                named_iofds,
4040                                fds,
4041                                n_socket_fds,
4042                                n_storage_fds,
4043                                files_env,
4044                                unit->manager->user_lookup_fds[1],
4045                                &exit_status);
4046
4047                 if (r < 0) {
4048                         const char *status =
4049                                 exit_status_to_string(exit_status,
4050                                                       EXIT_STATUS_LIBC | EXIT_STATUS_SYSTEMD);
4051
4052                         log_struct_errno(LOG_ERR, r,
4053                                          "MESSAGE_ID=" SD_MESSAGE_SPAWN_FAILED_STR,
4054                                          LOG_UNIT_ID(unit),
4055                                          LOG_UNIT_INVOCATION_ID(unit),
4056                                          LOG_UNIT_MESSAGE(unit, "Failed at step %s spawning %s: %m",
4057                                                           status, command->path),
4058                                          "EXECUTABLE=%s", command->path);
4059                 }
4060
4061                 _exit(exit_status);
4062         }
4063
4064         log_unit_debug(unit, "Forked %s as "PID_FMT, command->path, pid);
4065
4066         /* We add the new process to the cgroup both in the child (so that we can be sure that no user code is ever
4067          * executed outside of the cgroup) and in the parent (so that we can be sure that when we kill the cgroup the
4068          * process will be killed too). */
4069         if (subcgroup_path)
4070                 (void) cg_attach(SYSTEMD_CGROUP_CONTROLLER, subcgroup_path, pid);
4071
4072         exec_status_start(&command->exec_status, pid);
4073
4074         *ret = pid;
4075         return 0;
4076 }
4077
4078 void exec_context_init(ExecContext *c) {
4079         ExecDirectoryType i;
4080
4081         assert(c);
4082
4083         c->umask = 0022;
4084         c->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 0);
4085         c->cpu_sched_policy = SCHED_OTHER;
4086         c->syslog_priority = LOG_DAEMON|LOG_INFO;
4087         c->syslog_level_prefix = true;
4088         c->ignore_sigpipe = true;
4089         c->timer_slack_nsec = NSEC_INFINITY;
4090         c->personality = PERSONALITY_INVALID;
4091         for (i = 0; i < _EXEC_DIRECTORY_TYPE_MAX; i++)
4092                 c->directories[i].mode = 0755;
4093         c->timeout_clean_usec = USEC_INFINITY;
4094         c->capability_bounding_set = CAP_ALL;
4095         assert_cc(NAMESPACE_FLAGS_INITIAL != NAMESPACE_FLAGS_ALL);
4096         c->restrict_namespaces = NAMESPACE_FLAGS_INITIAL;
4097         c->log_level_max = -1;
4098         numa_policy_reset(&c->numa_policy);
4099 }
4100
4101 void exec_context_done(ExecContext *c) {
4102         ExecDirectoryType i;
4103         size_t l;
4104
4105         assert(c);
4106
4107         c->environment = strv_free(c->environment);
4108         c->environment_files = strv_free(c->environment_files);
4109         c->pass_environment = strv_free(c->pass_environment);
4110         c->unset_environment = strv_free(c->unset_environment);
4111
4112         rlimit_free_all(c->rlimit);
4113
4114         for (l = 0; l < 3; l++) {
4115                 c->stdio_fdname[l] = mfree(c->stdio_fdname[l]);
4116                 c->stdio_file[l] = mfree(c->stdio_file[l]);
4117         }
4118
4119         c->working_directory = mfree(c->working_directory);
4120         c->root_directory = mfree(c->root_directory);
4121         c->root_image = mfree(c->root_image);
4122         c->tty_path = mfree(c->tty_path);
4123         c->syslog_identifier = mfree(c->syslog_identifier);
4124         c->user = mfree(c->user);
4125         c->group = mfree(c->group);
4126
4127         c->supplementary_groups = strv_free(c->supplementary_groups);
4128
4129         c->pam_name = mfree(c->pam_name);
4130
4131         if (c->capabilities) {
4132                 cap_free(c->capabilities);
4133                 c->capabilities = NULL;
4134         }
4135
4136         c->read_only_paths = strv_free(c->read_only_paths);
4137         c->read_write_paths = strv_free(c->read_write_paths);
4138         c->inaccessible_paths = strv_free(c->inaccessible_paths);
4139
4140         bind_mount_free_many(c->bind_mounts, c->n_bind_mounts);
4141         c->bind_mounts = NULL;
4142         c->n_bind_mounts = 0;
4143         temporary_filesystem_free_many(c->temporary_filesystems, c->n_temporary_filesystems);
4144         c->temporary_filesystems = NULL;
4145         c->n_temporary_filesystems = 0;
4146
4147         cpu_set_reset(&c->cpu_set);
4148         numa_policy_reset(&c->numa_policy);
4149
4150         c->utmp_id = mfree(c->utmp_id);
4151         c->selinux_context = mfree(c->selinux_context);
4152         c->apparmor_profile = mfree(c->apparmor_profile);
4153         c->smack_process_label = mfree(c->smack_process_label);
4154
4155         c->syscall_filter = hashmap_free(c->syscall_filter);
4156         c->syscall_archs = set_free(c->syscall_archs);
4157         c->address_families = set_free(c->address_families);
4158
4159         for (i = 0; i < _EXEC_DIRECTORY_TYPE_MAX; i++)
4160                 c->directories[i].paths = strv_free(c->directories[i].paths);
4161
4162         c->log_level_max = -1;
4163
4164         exec_context_free_log_extra_fields(c);
4165
4166         c->log_ratelimit_interval_usec = 0;
4167         c->log_ratelimit_burst = 0;
4168
4169         c->stdin_data = mfree(c->stdin_data);
4170         c->stdin_data_size = 0;
4171
4172         c->network_namespace_path = mfree(c->network_namespace_path);
4173 }
4174
4175 int exec_context_destroy_runtime_directory(const ExecContext *c, const char *runtime_prefix) {
4176         char **i;
4177
4178         assert(c);
4179
4180         if (!runtime_prefix)
4181                 return 0;
4182
4183         STRV_FOREACH(i, c->directories[EXEC_DIRECTORY_RUNTIME].paths) {
4184                 _cleanup_free_ char *p;
4185
4186                 if (exec_directory_is_private(c, EXEC_DIRECTORY_RUNTIME))
4187                         p = path_join(runtime_prefix, "private", *i);
4188                 else
4189                         p = path_join(runtime_prefix, *i);
4190                 if (!p)
4191                         return -ENOMEM;
4192
4193                 /* We execute this synchronously, since we need to be sure this is gone when we start the
4194                  * service next. */
4195                 (void) rm_rf(p, REMOVE_ROOT);
4196         }
4197
4198         return 0;
4199 }
4200
4201 static void exec_command_done(ExecCommand *c) {
4202         assert(c);
4203
4204         c->path = mfree(c->path);
4205         c->argv = strv_free(c->argv);
4206 }
4207
4208 void exec_command_done_array(ExecCommand *c, size_t n) {
4209         size_t i;
4210
4211         for (i = 0; i < n; i++)
4212                 exec_command_done(c+i);
4213 }
4214
4215 ExecCommand* exec_command_free_list(ExecCommand *c) {
4216         ExecCommand *i;
4217
4218         while ((i = c)) {
4219                 LIST_REMOVE(command, c, i);
4220                 exec_command_done(i);
4221                 free(i);
4222         }
4223
4224         return NULL;
4225 }
4226
4227 void exec_command_free_array(ExecCommand **c, size_t n) {
4228         size_t i;
4229
4230         for (i = 0; i < n; i++)
4231                 c[i] = exec_command_free_list(c[i]);
4232 }
4233
4234 void exec_command_reset_status_array(ExecCommand *c, size_t n) {
4235         size_t i;
4236
4237         for (i = 0; i < n; i++)
4238                 exec_status_reset(&c[i].exec_status);
4239 }
4240
4241 void exec_command_reset_status_list_array(ExecCommand **c, size_t n) {
4242         size_t i;
4243
4244         for (i = 0; i < n; i++) {
4245                 ExecCommand *z;
4246
4247                 LIST_FOREACH(command, z, c[i])
4248                         exec_status_reset(&z->exec_status);
4249         }
4250 }
4251
4252 typedef struct InvalidEnvInfo {
4253         const Unit *unit;
4254         const char *path;
4255 } InvalidEnvInfo;
4256
4257 static void invalid_env(const char *p, void *userdata) {
4258         InvalidEnvInfo *info = userdata;
4259
4260         log_unit_error(info->unit, "Ignoring invalid environment assignment '%s': %s", p, info->path);
4261 }
4262
4263 const char* exec_context_fdname(const ExecContext *c, int fd_index) {
4264         assert(c);
4265
4266         switch (fd_index) {
4267
4268         case STDIN_FILENO:
4269                 if (c->std_input != EXEC_INPUT_NAMED_FD)
4270                         return NULL;
4271
4272                 return c->stdio_fdname[STDIN_FILENO] ?: "stdin";
4273
4274         case STDOUT_FILENO:
4275                 if (c->std_output != EXEC_OUTPUT_NAMED_FD)
4276                         return NULL;
4277
4278                 return c->stdio_fdname[STDOUT_FILENO] ?: "stdout";
4279
4280         case STDERR_FILENO:
4281                 if (c->std_error != EXEC_OUTPUT_NAMED_FD)
4282                         return NULL;
4283
4284                 return c->stdio_fdname[STDERR_FILENO] ?: "stderr";
4285
4286         default:
4287                 return NULL;
4288         }
4289 }
4290
4291 static int exec_context_named_iofds(
4292                 const ExecContext *c,
4293                 const ExecParameters *p,
4294                 int named_iofds[static 3]) {
4295
4296         size_t i, targets;
4297         const char* stdio_fdname[3];
4298         size_t n_fds;
4299
4300         assert(c);
4301         assert(p);
4302         assert(named_iofds);
4303
4304         targets = (c->std_input == EXEC_INPUT_NAMED_FD) +
4305                   (c->std_output == EXEC_OUTPUT_NAMED_FD) +
4306                   (c->std_error == EXEC_OUTPUT_NAMED_FD);
4307
4308         for (i = 0; i < 3; i++)
4309                 stdio_fdname[i] = exec_context_fdname(c, i);
4310
4311         n_fds = p->n_storage_fds + p->n_socket_fds;
4312
4313         for (i = 0; i < n_fds  && targets > 0; i++)
4314                 if (named_iofds[STDIN_FILENO] < 0 &&
4315                     c->std_input == EXEC_INPUT_NAMED_FD &&
4316                     stdio_fdname[STDIN_FILENO] &&
4317                     streq(p->fd_names[i], stdio_fdname[STDIN_FILENO])) {
4318
4319                         named_iofds[STDIN_FILENO] = p->fds[i];
4320                         targets--;
4321
4322                 } else if (named_iofds[STDOUT_FILENO] < 0 &&
4323                            c->std_output == EXEC_OUTPUT_NAMED_FD &&
4324                            stdio_fdname[STDOUT_FILENO] &&
4325                            streq(p->fd_names[i], stdio_fdname[STDOUT_FILENO])) {
4326
4327                         named_iofds[STDOUT_FILENO] = p->fds[i];
4328                         targets--;
4329
4330                 } else if (named_iofds[STDERR_FILENO] < 0 &&
4331                            c->std_error == EXEC_OUTPUT_NAMED_FD &&
4332                            stdio_fdname[STDERR_FILENO] &&
4333                            streq(p->fd_names[i], stdio_fdname[STDERR_FILENO])) {
4334
4335                         named_iofds[STDERR_FILENO] = p->fds[i];
4336                         targets--;
4337                 }
4338
4339         return targets == 0 ? 0 : -ENOENT;
4340 }
4341
4342 static int exec_context_load_environment(const Unit *unit, const ExecContext *c, char ***l) {
4343         char **i, **r = NULL;
4344
4345         assert(c);
4346         assert(l);
4347
4348         STRV_FOREACH(i, c->environment_files) {
4349                 char *fn;
4350                 int k;
4351                 unsigned n;
4352                 bool ignore = false;
4353                 char **p;
4354                 _cleanup_globfree_ glob_t pglob = {};
4355
4356                 fn = *i;
4357
4358                 if (fn[0] == '-') {
4359                         ignore = true;
4360                         fn++;
4361                 }
4362
4363                 if (!path_is_absolute(fn)) {
4364                         if (ignore)
4365                                 continue;
4366
4367                         strv_free(r);
4368                         return -EINVAL;
4369                 }
4370
4371                 /* Filename supports globbing, take all matching files */
4372                 k = safe_glob(fn, 0, &pglob);
4373                 if (k < 0) {
4374                         if (ignore)
4375                                 continue;
4376
4377                         strv_free(r);
4378                         return k;
4379                 }
4380
4381                 /* When we don't match anything, -ENOENT should be returned */
4382                 assert(pglob.gl_pathc > 0);
4383
4384                 for (n = 0; n < pglob.gl_pathc; n++) {
4385                         k = load_env_file(NULL, pglob.gl_pathv[n], &p);
4386                         if (k < 0) {
4387                                 if (ignore)
4388                                         continue;
4389
4390                                 strv_free(r);
4391                                 return k;
4392                         }
4393                         /* Log invalid environment variables with filename */
4394                         if (p) {
4395                                 InvalidEnvInfo info = {
4396                                         .unit = unit,
4397                                         .path = pglob.gl_pathv[n]
4398                                 };
4399
4400                                 p = strv_env_clean_with_callback(p, invalid_env, &info);
4401                         }
4402
4403                         if (!r)
4404                                 r = p;
4405                         else {
4406                                 char **m;
4407
4408                                 m = strv_env_merge(2, r, p);
4409                                 strv_free(r);
4410                                 strv_free(p);
4411                                 if (!m)
4412                                         return -ENOMEM;
4413
4414                                 r = m;
4415                         }
4416                 }
4417         }
4418
4419         *l = r;
4420
4421         return 0;
4422 }
4423
4424 static bool tty_may_match_dev_console(const char *tty) {
4425         _cleanup_free_ char *resolved = NULL;
4426
4427         if (!tty)
4428                 return true;
4429
4430         tty = skip_dev_prefix(tty);
4431
4432         /* trivial identity? */
4433         if (streq(tty, "console"))
4434                 return true;
4435
4436         if (resolve_dev_console(&resolved) < 0)
4437                 return true; /* if we could not resolve, assume it may */
4438
4439         /* "tty0" means the active VC, so it may be the same sometimes */
4440         return path_equal(resolved, tty) || (streq(resolved, "tty0") && tty_is_vc(tty));
4441 }
4442
4443 static bool exec_context_may_touch_tty(const ExecContext *ec) {
4444         assert(ec);
4445
4446         return ec->tty_reset ||
4447                 ec->tty_vhangup ||
4448                 ec->tty_vt_disallocate ||
4449                 is_terminal_input(ec->std_input) ||
4450                 is_terminal_output(ec->std_output) ||
4451                 is_terminal_output(ec->std_error);
4452 }
4453
4454 bool exec_context_may_touch_console(const ExecContext *ec) {
4455
4456         return exec_context_may_touch_tty(ec) &&
4457                tty_may_match_dev_console(exec_context_tty_path(ec));
4458 }
4459
4460 static void strv_fprintf(FILE *f, char **l) {
4461         char **g;
4462
4463         assert(f);
4464
4465         STRV_FOREACH(g, l)
4466                 fprintf(f, " %s", *g);
4467 }
4468
4469 void exec_context_dump(const ExecContext *c, FILE* f, const char *prefix) {
4470         char **e, **d, buf_clean[FORMAT_TIMESPAN_MAX];
4471         ExecDirectoryType dt;
4472         unsigned i;
4473         int r;
4474
4475         assert(c);
4476         assert(f);
4477
4478         prefix = strempty(prefix);
4479
4480         fprintf(f,
4481                 "%sUMask: %04o\n"
4482                 "%sWorkingDirectory: %s\n"
4483                 "%sRootDirectory: %s\n"
4484                 "%sNonBlocking: %s\n"
4485                 "%sPrivateTmp: %s\n"
4486                 "%sPrivateDevices: %s\n"
4487                 "%sProtectKernelTunables: %s\n"
4488                 "%sProtectKernelModules: %s\n"
4489                 "%sProtectKernelLogs: %s\n"
4490                 "%sProtectControlGroups: %s\n"
4491                 "%sPrivateNetwork: %s\n"
4492                 "%sPrivateUsers: %s\n"
4493                 "%sProtectHome: %s\n"
4494                 "%sProtectSystem: %s\n"
4495                 "%sMountAPIVFS: %s\n"
4496                 "%sIgnoreSIGPIPE: %s\n"
4497                 "%sMemoryDenyWriteExecute: %s\n"
4498                 "%sRestrictRealtime: %s\n"
4499                 "%sRestrictSUIDSGID: %s\n"
4500                 "%sKeyringMode: %s\n"
4501                 "%sProtectHostname: %s\n",
4502                 prefix, c->umask,
4503                 prefix, c->working_directory ? c->working_directory : "/",
4504                 prefix, c->root_directory ? c->root_directory : "/",
4505                 prefix, yes_no(c->non_blocking),
4506                 prefix, yes_no(c->private_tmp),
4507                 prefix, yes_no(c->private_devices),
4508                 prefix, yes_no(c->protect_kernel_tunables),
4509                 prefix, yes_no(c->protect_kernel_modules),
4510                 prefix, yes_no(c->protect_kernel_logs),
4511                 prefix, yes_no(c->protect_control_groups),
4512                 prefix, yes_no(c->private_network),
4513                 prefix, yes_no(c->private_users),
4514                 prefix, protect_home_to_string(c->protect_home),
4515                 prefix, protect_system_to_string(c->protect_system),
4516                 prefix, yes_no(c->mount_apivfs),
4517                 prefix, yes_no(c->ignore_sigpipe),
4518                 prefix, yes_no(c->memory_deny_write_execute),
4519                 prefix, yes_no(c->restrict_realtime),
4520                 prefix, yes_no(c->restrict_suid_sgid),
4521                 prefix, exec_keyring_mode_to_string(c->keyring_mode),
4522                 prefix, yes_no(c->protect_hostname));
4523
4524         if (c->root_image)
4525                 fprintf(f, "%sRootImage: %s\n", prefix, c->root_image);
4526
4527         STRV_FOREACH(e, c->environment)
4528                 fprintf(f, "%sEnvironment: %s\n", prefix, *e);
4529
4530         STRV_FOREACH(e, c->environment_files)
4531                 fprintf(f, "%sEnvironmentFile: %s\n", prefix, *e);
4532
4533         STRV_FOREACH(e, c->pass_environment)
4534                 fprintf(f, "%sPassEnvironment: %s\n", prefix, *e);
4535
4536         STRV_FOREACH(e, c->unset_environment)
4537                 fprintf(f, "%sUnsetEnvironment: %s\n", prefix, *e);
4538
4539         fprintf(f, "%sRuntimeDirectoryPreserve: %s\n", prefix, exec_preserve_mode_to_string(c->runtime_directory_preserve_mode));
4540
4541         for (dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
4542                 fprintf(f, "%s%sMode: %04o\n", prefix, exec_directory_type_to_string(dt), c->directories[dt].mode);
4543
4544                 STRV_FOREACH(d, c->directories[dt].paths)
4545                         fprintf(f, "%s%s: %s\n", prefix, exec_directory_type_to_string(dt), *d);
4546         }
4547
4548         fprintf(f,
4549                 "%sTimeoutCleanSec: %s\n",
4550                 prefix, format_timespan(buf_clean, sizeof(buf_clean), c->timeout_clean_usec, USEC_PER_SEC));
4551
4552         if (c->nice_set)
4553                 fprintf(f,
4554                         "%sNice: %i\n",
4555                         prefix, c->nice);
4556
4557         if (c->oom_score_adjust_set)
4558                 fprintf(f,
4559                         "%sOOMScoreAdjust: %i\n",
4560                         prefix, c->oom_score_adjust);
4561
4562         for (i = 0; i < RLIM_NLIMITS; i++)
4563                 if (c->rlimit[i]) {
4564                         fprintf(f, "%sLimit%s: " RLIM_FMT "\n",
4565                                 prefix, rlimit_to_string(i), c->rlimit[i]->rlim_max);
4566                         fprintf(f, "%sLimit%sSoft: " RLIM_FMT "\n",
4567                                 prefix, rlimit_to_string(i), c->rlimit[i]->rlim_cur);
4568                 }
4569
4570         if (c->ioprio_set) {
4571                 _cleanup_free_ char *class_str = NULL;
4572
4573                 r = ioprio_class_to_string_alloc(IOPRIO_PRIO_CLASS(c->ioprio), &class_str);
4574                 if (r >= 0)
4575                         fprintf(f, "%sIOSchedulingClass: %s\n", prefix, class_str);
4576
4577                 fprintf(f, "%sIOPriority: %lu\n", prefix, IOPRIO_PRIO_DATA(c->ioprio));
4578         }
4579
4580         if (c->cpu_sched_set) {
4581                 _cleanup_free_ char *policy_str = NULL;
4582
4583                 r = sched_policy_to_string_alloc(c->cpu_sched_policy, &policy_str);
4584                 if (r >= 0)
4585                         fprintf(f, "%sCPUSchedulingPolicy: %s\n", prefix, policy_str);
4586
4587                 fprintf(f,
4588                         "%sCPUSchedulingPriority: %i\n"
4589                         "%sCPUSchedulingResetOnFork: %s\n",
4590                         prefix, c->cpu_sched_priority,
4591                         prefix, yes_no(c->cpu_sched_reset_on_fork));
4592         }
4593
4594         if (c->cpu_set.set) {
4595                 _cleanup_free_ char *affinity = NULL;
4596
4597                 affinity = cpu_set_to_range_string(&c->cpu_set);
4598                 fprintf(f, "%sCPUAffinity: %s\n", prefix, affinity);
4599         }
4600
4601         if (mpol_is_valid(numa_policy_get_type(&c->numa_policy))) {
4602                 _cleanup_free_ char *nodes = NULL;
4603
4604                 nodes = cpu_set_to_range_string(&c->numa_policy.nodes);
4605                 fprintf(f, "%sNUMAPolicy: %s\n", prefix, mpol_to_string(numa_policy_get_type(&c->numa_policy)));
4606                 fprintf(f, "%sNUMAMask: %s\n", prefix, strnull(nodes));
4607         }
4608
4609         if (c->timer_slack_nsec != NSEC_INFINITY)
4610                 fprintf(f, "%sTimerSlackNSec: "NSEC_FMT "\n", prefix, c->timer_slack_nsec);
4611
4612         fprintf(f,
4613                 "%sStandardInput: %s\n"
4614                 "%sStandardOutput: %s\n"
4615                 "%sStandardError: %s\n",
4616                 prefix, exec_input_to_string(c->std_input),
4617                 prefix, exec_output_to_string(c->std_output),
4618                 prefix, exec_output_to_string(c->std_error));
4619
4620         if (c->std_input == EXEC_INPUT_NAMED_FD)
4621                 fprintf(f, "%sStandardInputFileDescriptorName: %s\n", prefix, c->stdio_fdname[STDIN_FILENO]);
4622         if (c->std_output == EXEC_OUTPUT_NAMED_FD)
4623                 fprintf(f, "%sStandardOutputFileDescriptorName: %s\n", prefix, c->stdio_fdname[STDOUT_FILENO]);
4624         if (c->std_error == EXEC_OUTPUT_NAMED_FD)
4625                 fprintf(f, "%sStandardErrorFileDescriptorName: %s\n", prefix, c->stdio_fdname[STDERR_FILENO]);
4626
4627         if (c->std_input == EXEC_INPUT_FILE)
4628                 fprintf(f, "%sStandardInputFile: %s\n", prefix, c->stdio_file[STDIN_FILENO]);
4629         if (c->std_output == EXEC_OUTPUT_FILE)
4630                 fprintf(f, "%sStandardOutputFile: %s\n", prefix, c->stdio_file[STDOUT_FILENO]);
4631         if (c->std_output == EXEC_OUTPUT_FILE_APPEND)
4632                 fprintf(f, "%sStandardOutputFileToAppend: %s\n", prefix, c->stdio_file[STDOUT_FILENO]);
4633         if (c->std_error == EXEC_OUTPUT_FILE)
4634                 fprintf(f, "%sStandardErrorFile: %s\n", prefix, c->stdio_file[STDERR_FILENO]);
4635         if (c->std_error == EXEC_OUTPUT_FILE_APPEND)
4636                 fprintf(f, "%sStandardErrorFileToAppend: %s\n", prefix, c->stdio_file[STDERR_FILENO]);
4637
4638         if (c->tty_path)
4639                 fprintf(f,
4640                         "%sTTYPath: %s\n"
4641                         "%sTTYReset: %s\n"
4642                         "%sTTYVHangup: %s\n"
4643                         "%sTTYVTDisallocate: %s\n",
4644                         prefix, c->tty_path,
4645                         prefix, yes_no(c->tty_reset),
4646                         prefix, yes_no(c->tty_vhangup),
4647                         prefix, yes_no(c->tty_vt_disallocate));
4648
4649         if (IN_SET(c->std_output,
4650                    EXEC_OUTPUT_SYSLOG,
4651                    EXEC_OUTPUT_KMSG,
4652                    EXEC_OUTPUT_JOURNAL,
4653                    EXEC_OUTPUT_SYSLOG_AND_CONSOLE,
4654                    EXEC_OUTPUT_KMSG_AND_CONSOLE,
4655                    EXEC_OUTPUT_JOURNAL_AND_CONSOLE) ||
4656             IN_SET(c->std_error,
4657                    EXEC_OUTPUT_SYSLOG,
4658                    EXEC_OUTPUT_KMSG,
4659                    EXEC_OUTPUT_JOURNAL,
4660                    EXEC_OUTPUT_SYSLOG_AND_CONSOLE,
4661                    EXEC_OUTPUT_KMSG_AND_CONSOLE,
4662                    EXEC_OUTPUT_JOURNAL_AND_CONSOLE)) {
4663
4664                 _cleanup_free_ char *fac_str = NULL, *lvl_str = NULL;
4665
4666                 r = log_facility_unshifted_to_string_alloc(c->syslog_priority >> 3, &fac_str);
4667                 if (r >= 0)
4668                         fprintf(f, "%sSyslogFacility: %s\n", prefix, fac_str);
4669
4670                 r = log_level_to_string_alloc(LOG_PRI(c->syslog_priority), &lvl_str);
4671                 if (r >= 0)
4672                         fprintf(f, "%sSyslogLevel: %s\n", prefix, lvl_str);
4673         }
4674
4675         if (c->capabilities) {
4676                 _cleanup_cap_free_charp_ char *t;
4677
4678                 t = cap_to_text(c->capabilities, NULL);
4679                 if (t)
4680                         fprintf(f, "%sCapabilities: %s\n", prefix, t);
4681         }
4682
4683         if (c->log_level_max >= 0) {
4684                 _cleanup_free_ char *t = NULL;
4685
4686                 (void) log_level_to_string_alloc(c->log_level_max, &t);
4687
4688                 fprintf(f, "%sLogLevelMax: %s\n", prefix, strna(t));
4689         }
4690
4691         if (c->log_ratelimit_interval_usec > 0) {
4692                 char buf_timespan[FORMAT_TIMESPAN_MAX];
4693
4694                 fprintf(f,
4695                         "%sLogRateLimitIntervalSec: %s\n",
4696                         prefix, format_timespan(buf_timespan, sizeof(buf_timespan), c->log_ratelimit_interval_usec, USEC_PER_SEC));
4697         }
4698
4699         if (c->log_ratelimit_burst > 0)
4700                 fprintf(f, "%sLogRateLimitBurst: %u\n", prefix, c->log_ratelimit_burst);
4701
4702         if (c->n_log_extra_fields > 0) {
4703                 size_t j;
4704
4705                 for (j = 0; j < c->n_log_extra_fields; j++) {
4706                         fprintf(f, "%sLogExtraFields: ", prefix);
4707                         fwrite(c->log_extra_fields[j].iov_base,
4708                                1, c->log_extra_fields[j].iov_len,
4709                                f);
4710                         fputc('\n', f);
4711                 }
4712         }
4713
4714         if (c->secure_bits) {
4715                 _cleanup_free_ char *str = NULL;
4716
4717                 r = secure_bits_to_string_alloc(c->secure_bits, &str);
4718                 if (r >= 0)
4719                         fprintf(f, "%sSecure Bits: %s\n", prefix, str);
4720         }
4721
4722         if (c->capability_bounding_set != CAP_ALL) {
4723                 _cleanup_free_ char *str = NULL;
4724
4725                 r = capability_set_to_string_alloc(c->capability_bounding_set, &str);
4726                 if (r >= 0)
4727                         fprintf(f, "%sCapabilityBoundingSet: %s\n", prefix, str);
4728         }
4729
4730         if (c->capability_ambient_set != 0) {
4731                 _cleanup_free_ char *str = NULL;
4732
4733                 r = capability_set_to_string_alloc(c->capability_ambient_set, &str);
4734                 if (r >= 0)
4735                         fprintf(f, "%sAmbientCapabilities: %s\n", prefix, str);
4736         }
4737
4738         if (c->user)
4739                 fprintf(f, "%sUser: %s\n", prefix, c->user);
4740         if (c->group)
4741                 fprintf(f, "%sGroup: %s\n", prefix, c->group);
4742
4743         fprintf(f, "%sDynamicUser: %s\n", prefix, yes_no(c->dynamic_user));
4744
4745         if (!strv_isempty(c->supplementary_groups)) {
4746                 fprintf(f, "%sSupplementaryGroups:", prefix);
4747                 strv_fprintf(f, c->supplementary_groups);
4748                 fputs("\n", f);
4749         }
4750
4751         if (c->pam_name)
4752                 fprintf(f, "%sPAMName: %s\n", prefix, c->pam_name);
4753
4754         if (!strv_isempty(c->read_write_paths)) {
4755                 fprintf(f, "%sReadWritePaths:", prefix);
4756                 strv_fprintf(f, c->read_write_paths);
4757                 fputs("\n", f);
4758         }
4759
4760         if (!strv_isempty(c->read_only_paths)) {
4761                 fprintf(f, "%sReadOnlyPaths:", prefix);
4762                 strv_fprintf(f, c->read_only_paths);
4763                 fputs("\n", f);
4764         }
4765
4766         if (!strv_isempty(c->inaccessible_paths)) {
4767                 fprintf(f, "%sInaccessiblePaths:", prefix);
4768                 strv_fprintf(f, c->inaccessible_paths);
4769                 fputs("\n", f);
4770         }
4771
4772         if (c->n_bind_mounts > 0)
4773                 for (i = 0; i < c->n_bind_mounts; i++)
4774                         fprintf(f, "%s%s: %s%s:%s:%s\n", prefix,
4775                                 c->bind_mounts[i].read_only ? "BindReadOnlyPaths" : "BindPaths",
4776                                 c->bind_mounts[i].ignore_enoent ? "-": "",
4777                                 c->bind_mounts[i].source,
4778                                 c->bind_mounts[i].destination,
4779                                 c->bind_mounts[i].recursive ? "rbind" : "norbind");
4780
4781         if (c->n_temporary_filesystems > 0)
4782                 for (i = 0; i < c->n_temporary_filesystems; i++) {
4783                         TemporaryFileSystem *t = c->temporary_filesystems + i;
4784
4785                         fprintf(f, "%sTemporaryFileSystem: %s%s%s\n", prefix,
4786                                 t->path,
4787                                 isempty(t->options) ? "" : ":",
4788                                 strempty(t->options));
4789                 }
4790
4791         if (c->utmp_id)
4792                 fprintf(f,
4793                         "%sUtmpIdentifier: %s\n",
4794                         prefix, c->utmp_id);
4795
4796         if (c->selinux_context)
4797                 fprintf(f,
4798                         "%sSELinuxContext: %s%s\n",
4799                         prefix, c->selinux_context_ignore ? "-" : "", c->selinux_context);
4800
4801         if (c->apparmor_profile)
4802                 fprintf(f,
4803                         "%sAppArmorProfile: %s%s\n",
4804                         prefix, c->apparmor_profile_ignore ? "-" : "", c->apparmor_profile);
4805
4806         if (c->smack_process_label)
4807                 fprintf(f,
4808                         "%sSmackProcessLabel: %s%s\n",
4809                         prefix, c->smack_process_label_ignore ? "-" : "", c->smack_process_label);
4810
4811         if (c->personality != PERSONALITY_INVALID)
4812                 fprintf(f,
4813                         "%sPersonality: %s\n",
4814                         prefix, strna(personality_to_string(c->personality)));
4815
4816         fprintf(f,
4817                 "%sLockPersonality: %s\n",
4818                 prefix, yes_no(c->lock_personality));
4819
4820         if (c->syscall_filter) {
4821 #if HAVE_SECCOMP
4822                 Iterator j;
4823                 void *id, *val;
4824                 bool first = true;
4825 #endif
4826
4827                 fprintf(f,
4828                         "%sSystemCallFilter: ",
4829                         prefix);
4830
4831                 if (!c->syscall_whitelist)
4832                         fputc('~', f);
4833
4834 #if HAVE_SECCOMP
4835                 HASHMAP_FOREACH_KEY(val, id, c->syscall_filter, j) {
4836                         _cleanup_free_ char *name = NULL;
4837                         const char *errno_name = NULL;
4838                         int num = PTR_TO_INT(val);
4839
4840                         if (first)
4841                                 first = false;
4842                         else
4843                                 fputc(' ', f);
4844
4845                         name = seccomp_syscall_resolve_num_arch(SCMP_ARCH_NATIVE, PTR_TO_INT(id) - 1);
4846                         fputs(strna(name), f);
4847
4848                         if (num >= 0) {
4849                                 errno_name = errno_to_name(num);
4850                                 if (errno_name)
4851                                         fprintf(f, ":%s", errno_name);
4852                                 else
4853                                         fprintf(f, ":%d", num);
4854                         }
4855                 }
4856 #endif
4857
4858                 fputc('\n', f);
4859         }
4860
4861         if (c->syscall_archs) {
4862 #if HAVE_SECCOMP
4863                 Iterator j;
4864                 void *id;
4865 #endif
4866
4867                 fprintf(f,
4868                         "%sSystemCallArchitectures:",
4869                         prefix);
4870
4871 #if HAVE_SECCOMP
4872                 SET_FOREACH(id, c->syscall_archs, j)
4873                         fprintf(f, " %s", strna(seccomp_arch_to_string(PTR_TO_UINT32(id) - 1)));
4874 #endif
4875                 fputc('\n', f);
4876         }
4877
4878         if (exec_context_restrict_namespaces_set(c)) {
4879                 _cleanup_free_ char *s = NULL;
4880
4881                 r = namespace_flags_to_string(c->restrict_namespaces, &s);
4882                 if (r >= 0)
4883                         fprintf(f, "%sRestrictNamespaces: %s\n",
4884                                 prefix, s);
4885         }
4886
4887         if (c->network_namespace_path)
4888                 fprintf(f,
4889                         "%sNetworkNamespacePath: %s\n",
4890                         prefix, c->network_namespace_path);
4891
4892         if (c->syscall_errno > 0) {
4893                 const char *errno_name;
4894
4895                 fprintf(f, "%sSystemCallErrorNumber: ", prefix);
4896
4897                 errno_name = errno_to_name(c->syscall_errno);
4898                 if (errno_name)
4899                         fprintf(f, "%s\n", errno_name);
4900                 else
4901                         fprintf(f, "%d\n", c->syscall_errno);
4902         }
4903 }
4904
4905 bool exec_context_maintains_privileges(const ExecContext *c) {
4906         assert(c);
4907
4908         /* Returns true if the process forked off would run under
4909          * an unchanged UID or as root. */
4910
4911         if (!c->user)
4912                 return true;
4913
4914         if (streq(c->user, "root") || streq(c->user, "0"))
4915                 return true;
4916
4917         return false;
4918 }
4919
4920 int exec_context_get_effective_ioprio(const ExecContext *c) {
4921         int p;
4922
4923         assert(c);
4924
4925         if (c->ioprio_set)
4926                 return c->ioprio;
4927
4928         p = ioprio_get(IOPRIO_WHO_PROCESS, 0);
4929         if (p < 0)
4930                 return IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 4);
4931
4932         return p;
4933 }
4934
4935 void exec_context_free_log_extra_fields(ExecContext *c) {
4936         size_t l;
4937
4938         assert(c);
4939
4940         for (l = 0; l < c->n_log_extra_fields; l++)
4941                 free(c->log_extra_fields[l].iov_base);
4942         c->log_extra_fields = mfree(c->log_extra_fields);
4943         c->n_log_extra_fields = 0;
4944 }
4945
4946 void exec_context_revert_tty(ExecContext *c) {
4947         int r;
4948
4949         assert(c);
4950
4951         /* First, reset the TTY (possibly kicking everybody else from the TTY) */
4952         exec_context_tty_reset(c, NULL);
4953
4954         /* And then undo what chown_terminal() did earlier. Note that we only do this if we have a path
4955          * configured. If the TTY was passed to us as file descriptor we assume the TTY is opened and managed
4956          * by whoever passed it to us and thus knows better when and how to chmod()/chown() it back. */
4957
4958         if (exec_context_may_touch_tty(c)) {
4959                 const char *path;
4960
4961                 path = exec_context_tty_path(c);
4962                 if (path) {
4963                         r = chmod_and_chown(path, TTY_MODE, 0, TTY_GID);
4964                         if (r < 0 && r != -ENOENT)
4965                                 log_warning_errno(r, "Failed to reset TTY ownership/access mode of %s, ignoring: %m", path);
4966                 }
4967         }
4968 }
4969
4970 int exec_context_get_clean_directories(
4971                 ExecContext *c,
4972                 char **prefix,
4973                 ExecCleanMask mask,
4974                 char ***ret) {
4975
4976         _cleanup_strv_free_ char **l = NULL;
4977         ExecDirectoryType t;
4978         int r;
4979
4980         assert(c);
4981         assert(prefix);
4982         assert(ret);
4983
4984         for (t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
4985                 char **i;
4986
4987                 if (!FLAGS_SET(mask, 1U << t))
4988                         continue;
4989
4990                 if (!prefix[t])
4991                         continue;
4992
4993                 STRV_FOREACH(i, c->directories[t].paths) {
4994                         char *j;
4995
4996                         j = path_join(prefix[t], *i);
4997                         if (!j)
4998                                 return -ENOMEM;
4999
5000                         r = strv_consume(&l, j);
5001                         if (r < 0)
5002                                 return r;
5003
5004                         /* Also remove private directories unconditionally. */
5005                         if (t != EXEC_DIRECTORY_CONFIGURATION) {
5006                                 j = path_join(prefix[t], "private", *i);
5007                                 if (!j)
5008                                         return -ENOMEM;
5009
5010                                 r = strv_consume(&l, j);
5011                                 if (r < 0)
5012                                         return r;
5013                         }
5014                 }
5015         }
5016
5017         *ret = TAKE_PTR(l);
5018         return 0;
5019 }
5020
5021 int exec_context_get_clean_mask(ExecContext *c, ExecCleanMask *ret) {
5022         ExecCleanMask mask = 0;
5023
5024         assert(c);
5025         assert(ret);
5026
5027         for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++)
5028                 if (!strv_isempty(c->directories[t].paths))
5029                         mask |= 1U << t;
5030
5031         *ret = mask;
5032         return 0;
5033 }
5034
5035 void exec_status_start(ExecStatus *s, pid_t pid) {
5036         assert(s);
5037
5038         *s = (ExecStatus) {
5039                 .pid = pid,
5040         };
5041
5042         dual_timestamp_get(&s->start_timestamp);
5043 }
5044
5045 void exec_status_exit(ExecStatus *s, const ExecContext *context, pid_t pid, int code, int status) {
5046         assert(s);
5047
5048         if (s->pid != pid) {
5049                 *s = (ExecStatus) {
5050                         .pid = pid,
5051                 };
5052         }
5053
5054         dual_timestamp_get(&s->exit_timestamp);
5055
5056         s->code = code;
5057         s->status = status;
5058
5059         if (context && context->utmp_id)
5060                 (void) utmp_put_dead_process(context->utmp_id, pid, code, status);
5061 }
5062
5063 void exec_status_reset(ExecStatus *s) {
5064         assert(s);
5065
5066         *s = (ExecStatus) {};
5067 }
5068
5069 void exec_status_dump(const ExecStatus *s, FILE *f, const char *prefix) {
5070         char buf[FORMAT_TIMESTAMP_MAX];
5071
5072         assert(s);
5073         assert(f);
5074
5075         if (s->pid <= 0)
5076                 return;
5077
5078         prefix = strempty(prefix);
5079
5080         fprintf(f,
5081                 "%sPID: "PID_FMT"\n",
5082                 prefix, s->pid);
5083
5084         if (dual_timestamp_is_set(&s->start_timestamp))
5085                 fprintf(f,
5086                         "%sStart Timestamp: %s\n",
5087                         prefix, format_timestamp(buf, sizeof(buf), s->start_timestamp.realtime));
5088
5089         if (dual_timestamp_is_set(&s->exit_timestamp))
5090                 fprintf(f,
5091                         "%sExit Timestamp: %s\n"
5092                         "%sExit Code: %s\n"
5093                         "%sExit Status: %i\n",
5094                         prefix, format_timestamp(buf, sizeof(buf), s->exit_timestamp.realtime),
5095                         prefix, sigchld_code_to_string(s->code),
5096                         prefix, s->status);
5097 }
5098
5099 static char *exec_command_line(char **argv) {
5100         size_t k;
5101         char *n, *p, **a;
5102         bool first = true;
5103
5104         assert(argv);
5105
5106         k = 1;
5107         STRV_FOREACH(a, argv)
5108                 k += strlen(*a)+3;
5109
5110         n = new(char, k);
5111         if (!n)
5112                 return NULL;
5113
5114         p = n;
5115         STRV_FOREACH(a, argv) {
5116
5117                 if (!first)
5118                         *(p++) = ' ';
5119                 else
5120                         first = false;
5121
5122                 if (strpbrk(*a, WHITESPACE)) {
5123                         *(p++) = '\'';
5124                         p = stpcpy(p, *a);
5125                         *(p++) = '\'';
5126                 } else
5127                         p = stpcpy(p, *a);
5128
5129         }
5130
5131         *p = 0;
5132
5133         /* FIXME: this doesn't really handle arguments that have
5134          * spaces and ticks in them */
5135
5136         return n;
5137 }
5138
5139 static void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
5140         _cleanup_free_ char *cmd = NULL;
5141         const char *prefix2;
5142
5143         assert(c);
5144         assert(f);
5145
5146         prefix = strempty(prefix);
5147         prefix2 = strjoina(prefix, "\t");
5148
5149         cmd = exec_command_line(c->argv);
5150         fprintf(f,
5151                 "%sCommand Line: %s\n",
5152                 prefix, cmd ? cmd : strerror_safe(ENOMEM));
5153
5154         exec_status_dump(&c->exec_status, f, prefix2);
5155 }
5156
5157 void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
5158         assert(f);
5159
5160         prefix = strempty(prefix);
5161
5162         LIST_FOREACH(command, c, c)
5163                 exec_command_dump(c, f, prefix);
5164 }
5165
5166 void exec_command_append_list(ExecCommand **l, ExecCommand *e) {
5167         ExecCommand *end;
5168
5169         assert(l);
5170         assert(e);
5171
5172         if (*l) {
5173                 /* It's kind of important, that we keep the order here */
5174                 LIST_FIND_TAIL(command, *l, end);
5175                 LIST_INSERT_AFTER(command, *l, end, e);
5176         } else
5177               *l = e;
5178 }
5179
5180 int exec_command_set(ExecCommand *c, const char *path, ...) {
5181         va_list ap;
5182         char **l, *p;
5183
5184         assert(c);
5185         assert(path);
5186
5187         va_start(ap, path);
5188         l = strv_new_ap(path, ap);
5189         va_end(ap);
5190
5191         if (!l)
5192                 return -ENOMEM;
5193
5194         p = strdup(path);
5195         if (!p) {
5196                 strv_free(l);
5197                 return -ENOMEM;
5198         }
5199
5200         free_and_replace(c->path, p);
5201
5202         return strv_free_and_replace(c->argv, l);
5203 }
5204
5205 int exec_command_append(ExecCommand *c, const char *path, ...) {
5206         _cleanup_strv_free_ char **l = NULL;
5207         va_list ap;
5208         int r;
5209
5210         assert(c);
5211         assert(path);
5212
5213         va_start(ap, path);
5214         l = strv_new_ap(path, ap);
5215         va_end(ap);
5216
5217         if (!l)
5218                 return -ENOMEM;
5219
5220         r = strv_extend_strv(&c->argv, l, false);
5221         if (r < 0)
5222                 return r;
5223
5224         return 0;
5225 }
5226
5227 static void *remove_tmpdir_thread(void *p) {
5228         _cleanup_free_ char *path = p;
5229
5230         (void) rm_rf(path, REMOVE_ROOT|REMOVE_PHYSICAL);
5231         return NULL;
5232 }
5233
5234 static ExecRuntime* exec_runtime_free(ExecRuntime *rt, bool destroy) {
5235         int r;
5236
5237         if (!rt)
5238                 return NULL;
5239
5240         if (rt->manager)
5241                 (void) hashmap_remove(rt->manager->exec_runtime_by_id, rt->id);
5242
5243         /* When destroy is true, then rm_rf tmp_dir and var_tmp_dir. */
5244         if (destroy && rt->tmp_dir) {
5245                 log_debug("Spawning thread to nuke %s", rt->tmp_dir);
5246
5247                 r = asynchronous_job(remove_tmpdir_thread, rt->tmp_dir);
5248                 if (r < 0) {
5249                         log_warning_errno(r, "Failed to nuke %s: %m", rt->tmp_dir);
5250                         free(rt->tmp_dir);
5251                 }
5252
5253                 rt->tmp_dir = NULL;
5254         }
5255
5256         if (destroy && rt->var_tmp_dir) {
5257                 log_debug("Spawning thread to nuke %s", rt->var_tmp_dir);
5258
5259                 r = asynchronous_job(remove_tmpdir_thread, rt->var_tmp_dir);
5260                 if (r < 0) {
5261                         log_warning_errno(r, "Failed to nuke %s: %m", rt->var_tmp_dir);
5262                         free(rt->var_tmp_dir);
5263                 }
5264
5265                 rt->var_tmp_dir = NULL;
5266         }
5267
5268         rt->id = mfree(rt->id);
5269         rt->tmp_dir = mfree(rt->tmp_dir);
5270         rt->var_tmp_dir = mfree(rt->var_tmp_dir);
5271         safe_close_pair(rt->netns_storage_socket);
5272         return mfree(rt);
5273 }
5274
5275 static void exec_runtime_freep(ExecRuntime **rt) {
5276         (void) exec_runtime_free(*rt, false);
5277 }
5278
5279 static int exec_runtime_allocate(ExecRuntime **ret) {
5280         ExecRuntime *n;
5281
5282         assert(ret);
5283
5284         n = new(ExecRuntime, 1);
5285         if (!n)
5286                 return -ENOMEM;
5287
5288         *n = (ExecRuntime) {
5289                 .netns_storage_socket = { -1, -1 },
5290         };
5291
5292         *ret = n;
5293         return 0;
5294 }
5295
5296 static int exec_runtime_add(
5297                 Manager *m,
5298                 const char *id,
5299                 const char *tmp_dir,
5300                 const char *var_tmp_dir,
5301                 const int netns_storage_socket[2],
5302                 ExecRuntime **ret) {
5303
5304         _cleanup_(exec_runtime_freep) ExecRuntime *rt = NULL;
5305         int r;
5306
5307         assert(m);
5308         assert(id);
5309
5310         r = hashmap_ensure_allocated(&m->exec_runtime_by_id, &string_hash_ops);
5311         if (r < 0)
5312                 return r;
5313
5314         r = exec_runtime_allocate(&rt);
5315         if (r < 0)
5316                 return r;
5317
5318         rt->id = strdup(id);
5319         if (!rt->id)
5320                 return -ENOMEM;
5321
5322         if (tmp_dir) {
5323                 rt->tmp_dir = strdup(tmp_dir);
5324                 if (!rt->tmp_dir)
5325                         return -ENOMEM;
5326
5327                 /* When tmp_dir is set, then we require var_tmp_dir is also set. */
5328                 assert(var_tmp_dir);
5329                 rt->var_tmp_dir = strdup(var_tmp_dir);
5330                 if (!rt->var_tmp_dir)
5331                         return -ENOMEM;
5332         }
5333
5334         if (netns_storage_socket) {
5335                 rt->netns_storage_socket[0] = netns_storage_socket[0];
5336                 rt->netns_storage_socket[1] = netns_storage_socket[1];
5337         }
5338
5339         r = hashmap_put(m->exec_runtime_by_id, rt->id, rt);
5340         if (r < 0)
5341                 return r;
5342
5343         rt->manager = m;
5344
5345         if (ret)
5346                 *ret = rt;
5347
5348         /* do not remove created ExecRuntime object when the operation succeeds. */
5349         rt = NULL;
5350         return 0;
5351 }
5352
5353 static int exec_runtime_make(Manager *m, const ExecContext *c, const char *id, ExecRuntime **ret) {
5354         _cleanup_free_ char *tmp_dir = NULL, *var_tmp_dir = NULL;
5355         _cleanup_close_pair_ int netns_storage_socket[2] = { -1, -1 };
5356         int r;
5357
5358         assert(m);
5359         assert(c);
5360         assert(id);
5361
5362         /* It is not necessary to create ExecRuntime object. */
5363         if (!c->private_network && !c->private_tmp && !c->network_namespace_path)
5364                 return 0;
5365
5366         if (c->private_tmp) {
5367                 r = setup_tmp_dirs(id, &tmp_dir, &var_tmp_dir);
5368                 if (r < 0)
5369                         return r;
5370         }
5371
5372         if (c->private_network || c->network_namespace_path) {
5373                 if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, netns_storage_socket) < 0)
5374                         return -errno;
5375         }
5376
5377         r = exec_runtime_add(m, id, tmp_dir, var_tmp_dir, netns_storage_socket, ret);
5378         if (r < 0)
5379                 return r;
5380
5381         /* Avoid cleanup */
5382         netns_storage_socket[0] = netns_storage_socket[1] = -1;
5383         return 1;
5384 }
5385
5386 int exec_runtime_acquire(Manager *m, const ExecContext *c, const char *id, bool create, ExecRuntime **ret) {
5387         ExecRuntime *rt;
5388         int r;
5389
5390         assert(m);
5391         assert(id);
5392         assert(ret);
5393
5394         rt = hashmap_get(m->exec_runtime_by_id, id);
5395         if (rt)
5396                 /* We already have a ExecRuntime object, let's increase the ref count and reuse it */
5397                 goto ref;
5398
5399         if (!create)
5400                 return 0;
5401
5402         /* If not found, then create a new object. */
5403         r = exec_runtime_make(m, c, id, &rt);
5404         if (r <= 0)
5405                 /* When r == 0, it is not necessary to create ExecRuntime object. */
5406                 return r;
5407
5408 ref:
5409         /* increment reference counter. */
5410         rt->n_ref++;
5411         *ret = rt;
5412         return 1;
5413 }
5414
5415 ExecRuntime *exec_runtime_unref(ExecRuntime *rt, bool destroy) {
5416         if (!rt)
5417                 return NULL;
5418
5419         assert(rt->n_ref > 0);
5420
5421         rt->n_ref--;
5422         if (rt->n_ref > 0)
5423                 return NULL;
5424
5425         return exec_runtime_free(rt, destroy);
5426 }
5427
5428 int exec_runtime_serialize(const Manager *m, FILE *f, FDSet *fds) {
5429         ExecRuntime *rt;
5430         Iterator i;
5431
5432         assert(m);
5433         assert(f);
5434         assert(fds);
5435
5436         HASHMAP_FOREACH(rt, m->exec_runtime_by_id, i) {
5437                 fprintf(f, "exec-runtime=%s", rt->id);
5438
5439                 if (rt->tmp_dir)
5440                         fprintf(f, " tmp-dir=%s", rt->tmp_dir);
5441
5442                 if (rt->var_tmp_dir)
5443                         fprintf(f, " var-tmp-dir=%s", rt->var_tmp_dir);
5444
5445                 if (rt->netns_storage_socket[0] >= 0) {
5446                         int copy;
5447
5448                         copy = fdset_put_dup(fds, rt->netns_storage_socket[0]);
5449                         if (copy < 0)
5450                                 return copy;
5451
5452                         fprintf(f, " netns-socket-0=%i", copy);
5453                 }
5454
5455                 if (rt->netns_storage_socket[1] >= 0) {
5456                         int copy;
5457
5458                         copy = fdset_put_dup(fds, rt->netns_storage_socket[1]);
5459                         if (copy < 0)
5460                                 return copy;
5461
5462                         fprintf(f, " netns-socket-1=%i", copy);
5463                 }
5464
5465                 fputc('\n', f);
5466         }
5467
5468         return 0;
5469 }
5470
5471 int exec_runtime_deserialize_compat(Unit *u, const char *key, const char *value, FDSet *fds) {
5472         _cleanup_(exec_runtime_freep) ExecRuntime *rt_create = NULL;
5473         ExecRuntime *rt;
5474         int r;
5475
5476         /* This is for the migration from old (v237 or earlier) deserialization text.
5477          * Due to the bug #7790, this may not work with the units that use JoinsNamespaceOf=.
5478          * Even if the ExecRuntime object originally created by the other unit, we cannot judge
5479          * so or not from the serialized text, then we always creates a new object owned by this. */
5480
5481         assert(u);
5482         assert(key);
5483         assert(value);
5484
5485         /* Manager manages ExecRuntime objects by the unit id.
5486          * So, we omit the serialized text when the unit does not have id (yet?)... */
5487         if (isempty(u->id)) {
5488                 log_unit_debug(u, "Invocation ID not found. Dropping runtime parameter.");
5489                 return 0;
5490         }
5491
5492         r = hashmap_ensure_allocated(&u->manager->exec_runtime_by_id, &string_hash_ops);
5493         if (r < 0) {
5494                 log_unit_debug_errno(u, r, "Failed to allocate storage for runtime parameter: %m");
5495                 return 0;
5496         }
5497
5498         rt = hashmap_get(u->manager->exec_runtime_by_id, u->id);
5499         if (!rt) {
5500                 r = exec_runtime_allocate(&rt_create);
5501                 if (r < 0)
5502                         return log_oom();
5503
5504                 rt_create->id = strdup(u->id);
5505                 if (!rt_create->id)
5506                         return log_oom();
5507
5508                 rt = rt_create;
5509         }
5510
5511         if (streq(key, "tmp-dir")) {
5512                 char *copy;
5513
5514                 copy = strdup(value);
5515                 if (!copy)
5516                         return log_oom();
5517
5518                 free_and_replace(rt->tmp_dir, copy);
5519
5520         } else if (streq(key, "var-tmp-dir")) {
5521                 char *copy;
5522
5523                 copy = strdup(value);
5524                 if (!copy)
5525                         return log_oom();
5526
5527                 free_and_replace(rt->var_tmp_dir, copy);
5528
5529         } else if (streq(key, "netns-socket-0")) {
5530                 int fd;
5531
5532                 if (safe_atoi(value, &fd) < 0 || !fdset_contains(fds, fd)) {
5533                         log_unit_debug(u, "Failed to parse netns socket value: %s", value);
5534                         return 0;
5535                 }
5536
5537                 safe_close(rt->netns_storage_socket[0]);
5538                 rt->netns_storage_socket[0] = fdset_remove(fds, fd);
5539
5540         } else if (streq(key, "netns-socket-1")) {
5541                 int fd;
5542
5543                 if (safe_atoi(value, &fd) < 0 || !fdset_contains(fds, fd)) {
5544                         log_unit_debug(u, "Failed to parse netns socket value: %s", value);
5545                         return 0;
5546                 }
5547
5548                 safe_close(rt->netns_storage_socket[1]);
5549                 rt->netns_storage_socket[1] = fdset_remove(fds, fd);
5550         } else
5551                 return 0;
5552
5553         /* If the object is newly created, then put it to the hashmap which manages ExecRuntime objects. */
5554         if (rt_create) {
5555                 r = hashmap_put(u->manager->exec_runtime_by_id, rt_create->id, rt_create);
5556                 if (r < 0) {
5557                         log_unit_debug_errno(u, r, "Failed to put runtime parameter to manager's storage: %m");
5558                         return 0;
5559                 }
5560
5561                 rt_create->manager = u->manager;
5562
5563                 /* Avoid cleanup */
5564                 rt_create = NULL;
5565         }
5566
5567         return 1;
5568 }
5569
5570 void exec_runtime_deserialize_one(Manager *m, const char *value, FDSet *fds) {
5571         char *id = NULL, *tmp_dir = NULL, *var_tmp_dir = NULL;
5572         int r, fd0 = -1, fd1 = -1;
5573         const char *p, *v = value;
5574         size_t n;
5575
5576         assert(m);
5577         assert(value);
5578         assert(fds);
5579
5580         n = strcspn(v, " ");
5581         id = strndupa(v, n);
5582         if (v[n] != ' ')
5583                 goto finalize;
5584         p = v + n + 1;
5585
5586         v = startswith(p, "tmp-dir=");
5587         if (v) {
5588                 n = strcspn(v, " ");
5589                 tmp_dir = strndupa(v, n);
5590                 if (v[n] != ' ')
5591                         goto finalize;
5592                 p = v + n + 1;
5593         }
5594
5595         v = startswith(p, "var-tmp-dir=");
5596         if (v) {
5597                 n = strcspn(v, " ");
5598                 var_tmp_dir = strndupa(v, n);
5599                 if (v[n] != ' ')
5600                         goto finalize;
5601                 p = v + n + 1;
5602         }
5603
5604         v = startswith(p, "netns-socket-0=");
5605         if (v) {
5606                 char *buf;
5607
5608                 n = strcspn(v, " ");
5609                 buf = strndupa(v, n);
5610                 if (safe_atoi(buf, &fd0) < 0 || !fdset_contains(fds, fd0)) {
5611                         log_debug("Unable to process exec-runtime netns fd specification.");
5612                         return;
5613                 }
5614                 fd0 = fdset_remove(fds, fd0);
5615                 if (v[n] != ' ')
5616                         goto finalize;
5617                 p = v + n + 1;
5618         }
5619
5620         v = startswith(p, "netns-socket-1=");
5621         if (v) {
5622                 char *buf;
5623
5624                 n = strcspn(v, " ");
5625                 buf = strndupa(v, n);
5626                 if (safe_atoi(buf, &fd1) < 0 || !fdset_contains(fds, fd1)) {
5627                         log_debug("Unable to process exec-runtime netns fd specification.");
5628                         return;
5629                 }
5630                 fd1 = fdset_remove(fds, fd1);
5631         }
5632
5633 finalize:
5634
5635         r = exec_runtime_add(m, id, tmp_dir, var_tmp_dir, (int[]) { fd0, fd1 }, NULL);
5636         if (r < 0)
5637                 log_debug_errno(r, "Failed to add exec-runtime: %m");
5638 }
5639
5640 void exec_runtime_vacuum(Manager *m) {
5641         ExecRuntime *rt;
5642         Iterator i;
5643
5644         assert(m);
5645
5646         /* Free unreferenced ExecRuntime objects. This is used after manager deserialization process. */
5647
5648         HASHMAP_FOREACH(rt, m->exec_runtime_by_id, i) {
5649                 if (rt->n_ref > 0)
5650                         continue;
5651
5652                 (void) exec_runtime_free(rt, false);
5653         }
5654 }
5655
5656 void exec_params_clear(ExecParameters *p) {
5657         if (!p)
5658                 return;
5659
5660         strv_free(p->environment);
5661 }
5662
5663 static const char* const exec_input_table[_EXEC_INPUT_MAX] = {
5664         [EXEC_INPUT_NULL] = "null",
5665         [EXEC_INPUT_TTY] = "tty",
5666         [EXEC_INPUT_TTY_FORCE] = "tty-force",
5667         [EXEC_INPUT_TTY_FAIL] = "tty-fail",
5668         [EXEC_INPUT_SOCKET] = "socket",
5669         [EXEC_INPUT_NAMED_FD] = "fd",
5670         [EXEC_INPUT_DATA] = "data",
5671         [EXEC_INPUT_FILE] = "file",
5672 };
5673
5674 DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput);
5675
5676 static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = {
5677         [EXEC_OUTPUT_INHERIT] = "inherit",
5678         [EXEC_OUTPUT_NULL] = "null",
5679         [EXEC_OUTPUT_TTY] = "tty",
5680         [EXEC_OUTPUT_SYSLOG] = "syslog",
5681         [EXEC_OUTPUT_SYSLOG_AND_CONSOLE] = "syslog+console",
5682         [EXEC_OUTPUT_KMSG] = "kmsg",
5683         [EXEC_OUTPUT_KMSG_AND_CONSOLE] = "kmsg+console",
5684         [EXEC_OUTPUT_JOURNAL] = "journal",
5685         [EXEC_OUTPUT_JOURNAL_AND_CONSOLE] = "journal+console",
5686         [EXEC_OUTPUT_SOCKET] = "socket",
5687         [EXEC_OUTPUT_NAMED_FD] = "fd",
5688         [EXEC_OUTPUT_FILE] = "file",
5689         [EXEC_OUTPUT_FILE_APPEND] = "append",
5690         [EXEC_OUTPUT_DLOG] = "dlog",
5691         [EXEC_OUTPUT_DLOG_OR_NULL] = "dlog|null",
5692         [EXEC_OUTPUT_DLOG_OR_KMSG] = "dlog|kmsg",
5693         [EXEC_OUTPUT_DLOG_OR_JOURNAL] = "dlog|journal",
5694 };
5695
5696 DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput);
5697
5698 static const char* const exec_utmp_mode_table[_EXEC_UTMP_MODE_MAX] = {
5699         [EXEC_UTMP_INIT] = "init",
5700         [EXEC_UTMP_LOGIN] = "login",
5701         [EXEC_UTMP_USER] = "user",
5702 };
5703
5704 DEFINE_STRING_TABLE_LOOKUP(exec_utmp_mode, ExecUtmpMode);
5705
5706 static const char* const exec_preserve_mode_table[_EXEC_PRESERVE_MODE_MAX] = {
5707         [EXEC_PRESERVE_NO] = "no",
5708         [EXEC_PRESERVE_YES] = "yes",
5709         [EXEC_PRESERVE_RESTART] = "restart",
5710 };
5711
5712 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(exec_preserve_mode, ExecPreserveMode, EXEC_PRESERVE_YES);
5713
5714 /* This table maps ExecDirectoryType to the setting it is configured with in the unit */
5715 static const char* const exec_directory_type_table[_EXEC_DIRECTORY_TYPE_MAX] = {
5716         [EXEC_DIRECTORY_RUNTIME] = "RuntimeDirectory",
5717         [EXEC_DIRECTORY_STATE] = "StateDirectory",
5718         [EXEC_DIRECTORY_CACHE] = "CacheDirectory",
5719         [EXEC_DIRECTORY_LOGS] = "LogsDirectory",
5720         [EXEC_DIRECTORY_CONFIGURATION] = "ConfigurationDirectory",
5721 };
5722
5723 DEFINE_STRING_TABLE_LOOKUP(exec_directory_type, ExecDirectoryType);
5724
5725 /* And this table maps ExecDirectoryType too, but to a generic term identifying the type of resource. This
5726  * one is supposed to be generic enough to be used for unit types that don't use ExecContext and per-unit
5727  * directories, specifically .timer units with their timestamp touch file. */
5728 static const char* const exec_resource_type_table[_EXEC_DIRECTORY_TYPE_MAX] = {
5729         [EXEC_DIRECTORY_RUNTIME] = "runtime",
5730         [EXEC_DIRECTORY_STATE] = "state",
5731         [EXEC_DIRECTORY_CACHE] = "cache",
5732         [EXEC_DIRECTORY_LOGS] = "logs",
5733         [EXEC_DIRECTORY_CONFIGURATION] = "configuration",
5734 };
5735
5736 DEFINE_STRING_TABLE_LOOKUP(exec_resource_type, ExecDirectoryType);
5737
5738 /* And this table also maps ExecDirectoryType, to the environment variable we pass the selected directory to
5739  * the service payload in. */
5740 static const char* const exec_directory_env_name_table[_EXEC_DIRECTORY_TYPE_MAX] = {
5741         [EXEC_DIRECTORY_RUNTIME] = "RUNTIME_DIRECTORY",
5742         [EXEC_DIRECTORY_STATE] = "STATE_DIRECTORY",
5743         [EXEC_DIRECTORY_CACHE] = "CACHE_DIRECTORY",
5744         [EXEC_DIRECTORY_LOGS] = "LOGS_DIRECTORY",
5745         [EXEC_DIRECTORY_CONFIGURATION] = "CONFIGURATION_DIRECTORY",
5746 };
5747
5748 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(exec_directory_env_name, ExecDirectoryType);
5749
5750 static const char* const exec_keyring_mode_table[_EXEC_KEYRING_MODE_MAX] = {
5751         [EXEC_KEYRING_INHERIT] = "inherit",
5752         [EXEC_KEYRING_PRIVATE] = "private",
5753         [EXEC_KEYRING_SHARED] = "shared",
5754 };
5755
5756 DEFINE_STRING_TABLE_LOOKUP(exec_keyring_mode, ExecKeyringMode);