2 This file is part of systemd.
4 Copyright 2010 Lennart Poettering
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
27 #include <sys/capability.h>
28 #include <sys/eventfd.h>
30 #include <sys/personality.h>
31 #include <sys/prctl.h>
33 #include <sys/socket.h>
35 #include <sys/types.h>
41 #include <security/pam_appl.h>
45 #include <selinux/selinux.h>
53 #include <sys/apparmor.h>
56 #include "sd-messages.h"
59 #include "alloc-util.h"
61 #include "apparmor-util.h"
66 #include "capability-util.h"
69 #include "errno-list.h"
71 #include "exit-status.h"
74 #include "formats-util.h"
76 #include "glob-util.h"
83 #include "namespace.h"
84 #include "parse-util.h"
85 #include "path-util.h"
86 #include "process-util.h"
87 #include "rlimit-util.h"
90 #include "seccomp-util.h"
92 #include "securebits.h"
93 #include "selinux-util.h"
94 #include "signal-util.h"
95 #include "smack-util.h"
97 #include "string-table.h"
98 #include "string-util.h"
100 #include "syslog-util.h"
101 #include "terminal-util.h"
103 #include "user-util.h"
105 #include "utmp-wtmp.h"
107 #define IDLE_TIMEOUT_USEC (5*USEC_PER_SEC)
108 #define IDLE_TIMEOUT2_USEC (1*USEC_PER_SEC)
110 /* This assumes there is a 'tty' group */
111 #define TTY_MODE 0620
113 #define SNDBUF_SIZE (8*1024*1024)
115 static int shift_fds(int fds
[], unsigned n_fds
) {
116 int start
, restart_from
;
121 /* Modifies the fds array! (sorts it) */
131 for (i
= start
; i
< (int) n_fds
; i
++) {
134 /* Already at right index? */
138 nfd
= fcntl(fds
[i
], F_DUPFD
, i
+ 3);
145 /* Hmm, the fd we wanted isn't free? Then
146 * let's remember that and try again from here */
147 if (nfd
!= i
+3 && restart_from
< 0)
151 if (restart_from
< 0)
154 start
= restart_from
;
160 static int flags_fds(const int fds
[], unsigned n_fds
, bool nonblock
) {
169 /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags */
171 for (i
= 0; i
< n_fds
; i
++) {
173 r
= fd_nonblock(fds
[i
], nonblock
);
177 /* We unconditionally drop FD_CLOEXEC from the fds,
178 * since after all we want to pass these fds to our
181 r
= fd_cloexec(fds
[i
], false);
189 static const char *exec_context_tty_path(const ExecContext
*context
) {
192 if (context
->stdio_as_fds
)
195 if (context
->tty_path
)
196 return context
->tty_path
;
198 return "/dev/console";
201 static void exec_context_tty_reset(const ExecContext
*context
, const ExecParameters
*p
) {
206 path
= exec_context_tty_path(context
);
208 if (context
->tty_vhangup
) {
209 if (p
&& p
->stdin_fd
>= 0)
210 (void) terminal_vhangup_fd(p
->stdin_fd
);
212 (void) terminal_vhangup(path
);
215 if (context
->tty_reset
) {
216 if (p
&& p
->stdin_fd
>= 0)
217 (void) reset_terminal_fd(p
->stdin_fd
, true);
219 (void) reset_terminal(path
);
222 if (context
->tty_vt_disallocate
&& path
)
223 (void) vt_disallocate(path
);
226 static bool is_terminal_input(ExecInput i
) {
229 EXEC_INPUT_TTY_FORCE
,
230 EXEC_INPUT_TTY_FAIL
);
233 static bool is_terminal_output(ExecOutput o
) {
236 EXEC_OUTPUT_SYSLOG_AND_CONSOLE
,
237 EXEC_OUTPUT_KMSG_AND_CONSOLE
,
238 EXEC_OUTPUT_JOURNAL_AND_CONSOLE
);
241 static bool exec_context_needs_term(const ExecContext
*c
) {
244 /* Return true if the execution context suggests we should set $TERM to something useful. */
246 if (is_terminal_input(c
->std_input
))
249 if (is_terminal_output(c
->std_output
))
252 if (is_terminal_output(c
->std_error
))
255 return !!c
->tty_path
;
258 static int open_null_as(int flags
, int nfd
) {
263 fd
= open("/dev/null", flags
|O_NOCTTY
);
268 r
= dup2(fd
, nfd
) < 0 ? -errno
: nfd
;
276 static int connect_journal_socket(int fd
, uid_t uid
, gid_t gid
) {
277 union sockaddr_union sa
= {
278 .un
.sun_family
= AF_UNIX
,
279 .un
.sun_path
= "/run/systemd/journal/stdout",
281 uid_t olduid
= UID_INVALID
;
282 gid_t oldgid
= GID_INVALID
;
285 if (gid
!= GID_INVALID
) {
293 if (uid
!= UID_INVALID
) {
303 r
= connect(fd
, &sa
.sa
, SOCKADDR_UN_LEN(sa
.un
));
307 /* If we fail to restore the uid or gid, things will likely
308 fail later on. This should only happen if an LSM interferes. */
310 if (uid
!= UID_INVALID
)
311 (void) seteuid(olduid
);
314 if (gid
!= GID_INVALID
)
315 (void) setegid(oldgid
);
320 static int connect_logger_as(
322 const ExecContext
*context
,
332 assert(output
< _EXEC_OUTPUT_MAX
);
336 fd
= socket(AF_UNIX
, SOCK_STREAM
, 0);
340 r
= connect_journal_socket(fd
, uid
, gid
);
344 if (shutdown(fd
, SHUT_RD
) < 0) {
349 (void) fd_inc_sndbuf(fd
, SNDBUF_SIZE
);
359 context
->syslog_identifier
? context
->syslog_identifier
: ident
,
361 context
->syslog_priority
,
362 !!context
->syslog_level_prefix
,
363 output
== EXEC_OUTPUT_SYSLOG
|| output
== EXEC_OUTPUT_SYSLOG_AND_CONSOLE
,
364 output
== EXEC_OUTPUT_KMSG
|| output
== EXEC_OUTPUT_KMSG_AND_CONSOLE
,
365 is_terminal_output(output
));
370 r
= dup2(fd
, nfd
) < 0 ? -errno
: nfd
;
375 static int open_terminal_as(const char *path
, mode_t mode
, int nfd
) {
381 fd
= open_terminal(path
, mode
| O_NOCTTY
);
386 r
= dup2(fd
, nfd
) < 0 ? -errno
: nfd
;
394 static int fixup_input(ExecInput std_input
, int socket_fd
, bool apply_tty_stdin
) {
396 if (is_terminal_input(std_input
) && !apply_tty_stdin
)
397 return EXEC_INPUT_NULL
;
399 if (std_input
== EXEC_INPUT_SOCKET
&& socket_fd
< 0)
400 return EXEC_INPUT_NULL
;
405 static int fixup_output(ExecOutput std_output
, int socket_fd
) {
407 if (std_output
== EXEC_OUTPUT_SOCKET
&& socket_fd
< 0)
408 return EXEC_OUTPUT_INHERIT
;
413 static int setup_input(
414 const ExecContext
*context
,
415 const ExecParameters
*params
,
417 int named_iofds
[3]) {
424 if (params
->stdin_fd
>= 0) {
425 if (dup2(params
->stdin_fd
, STDIN_FILENO
) < 0)
428 /* Try to make this the controlling tty, if it is a tty, and reset it */
429 (void) ioctl(STDIN_FILENO
, TIOCSCTTY
, context
->std_input
== EXEC_INPUT_TTY_FORCE
);
430 (void) reset_terminal_fd(STDIN_FILENO
, true);
435 i
= fixup_input(context
->std_input
, socket_fd
, params
->flags
& EXEC_APPLY_TTY_STDIN
);
439 case EXEC_INPUT_NULL
:
440 return open_null_as(O_RDONLY
, STDIN_FILENO
);
443 case EXEC_INPUT_TTY_FORCE
:
444 case EXEC_INPUT_TTY_FAIL
: {
447 fd
= acquire_terminal(exec_context_tty_path(context
),
448 i
== EXEC_INPUT_TTY_FAIL
,
449 i
== EXEC_INPUT_TTY_FORCE
,
455 if (fd
!= STDIN_FILENO
) {
456 r
= dup2(fd
, STDIN_FILENO
) < 0 ? -errno
: STDIN_FILENO
;
464 case EXEC_INPUT_SOCKET
:
465 return dup2(socket_fd
, STDIN_FILENO
) < 0 ? -errno
: STDIN_FILENO
;
467 case EXEC_INPUT_NAMED_FD
:
468 (void) fd_nonblock(named_iofds
[STDIN_FILENO
], false);
469 return dup2(named_iofds
[STDIN_FILENO
], STDIN_FILENO
) < 0 ? -errno
: STDIN_FILENO
;
472 assert_not_reached("Unknown input type");
476 static int setup_output(
478 const ExecContext
*context
,
479 const ExecParameters
*params
,
486 dev_t
*journal_stream_dev
,
487 ino_t
*journal_stream_ino
) {
497 assert(journal_stream_dev
);
498 assert(journal_stream_ino
);
500 if (fileno
== STDOUT_FILENO
&& params
->stdout_fd
>= 0) {
502 if (dup2(params
->stdout_fd
, STDOUT_FILENO
) < 0)
505 return STDOUT_FILENO
;
508 if (fileno
== STDERR_FILENO
&& params
->stderr_fd
>= 0) {
509 if (dup2(params
->stderr_fd
, STDERR_FILENO
) < 0)
512 return STDERR_FILENO
;
515 i
= fixup_input(context
->std_input
, socket_fd
, params
->flags
& EXEC_APPLY_TTY_STDIN
);
516 o
= fixup_output(context
->std_output
, socket_fd
);
518 if (fileno
== STDERR_FILENO
) {
520 e
= fixup_output(context
->std_error
, socket_fd
);
522 /* This expects the input and output are already set up */
524 /* Don't change the stderr file descriptor if we inherit all
525 * the way and are not on a tty */
526 if (e
== EXEC_OUTPUT_INHERIT
&&
527 o
== EXEC_OUTPUT_INHERIT
&&
528 i
== EXEC_INPUT_NULL
&&
529 !is_terminal_input(context
->std_input
) &&
533 /* Duplicate from stdout if possible */
534 if ((e
== o
&& e
!= EXEC_OUTPUT_NAMED_FD
) || e
== EXEC_OUTPUT_INHERIT
)
535 return dup2(STDOUT_FILENO
, fileno
) < 0 ? -errno
: fileno
;
539 } else if (o
== EXEC_OUTPUT_INHERIT
) {
540 /* If input got downgraded, inherit the original value */
541 if (i
== EXEC_INPUT_NULL
&& is_terminal_input(context
->std_input
))
542 return open_terminal_as(exec_context_tty_path(context
), O_WRONLY
, fileno
);
544 /* If the input is connected to anything that's not a /dev/null, inherit that... */
545 if (i
!= EXEC_INPUT_NULL
)
546 return dup2(STDIN_FILENO
, fileno
) < 0 ? -errno
: fileno
;
548 /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */
552 /* We need to open /dev/null here anew, to get the right access mode. */
553 return open_null_as(O_WRONLY
, fileno
);
558 case EXEC_OUTPUT_NULL
:
559 return open_null_as(O_WRONLY
, fileno
);
561 case EXEC_OUTPUT_TTY
:
562 if (is_terminal_input(i
))
563 return dup2(STDIN_FILENO
, fileno
) < 0 ? -errno
: fileno
;
565 /* We don't reset the terminal if this is just about output */
566 return open_terminal_as(exec_context_tty_path(context
), O_WRONLY
, fileno
);
568 case EXEC_OUTPUT_SYSLOG
:
569 case EXEC_OUTPUT_SYSLOG_AND_CONSOLE
:
570 case EXEC_OUTPUT_KMSG
:
571 case EXEC_OUTPUT_KMSG_AND_CONSOLE
:
572 case EXEC_OUTPUT_JOURNAL
:
573 case EXEC_OUTPUT_JOURNAL_AND_CONSOLE
:
574 r
= connect_logger_as(unit
, context
, o
, ident
, fileno
, uid
, gid
);
576 log_unit_error_errno(unit
, r
, "Failed to connect %s to the journal socket, ignoring: %m", fileno
== STDOUT_FILENO
? "stdout" : "stderr");
577 r
= open_null_as(O_WRONLY
, fileno
);
581 /* If we connected this fd to the journal via a stream, patch the device/inode into the passed
582 * parameters, but only then. This is useful so that we can set $JOURNAL_STREAM that permits
583 * services to detect whether they are connected to the journal or not. */
585 if (fstat(fileno
, &st
) >= 0) {
586 *journal_stream_dev
= st
.st_dev
;
587 *journal_stream_ino
= st
.st_ino
;
592 case EXEC_OUTPUT_SOCKET
:
593 assert(socket_fd
>= 0);
594 return dup2(socket_fd
, fileno
) < 0 ? -errno
: fileno
;
596 case EXEC_OUTPUT_NAMED_FD
:
597 (void) fd_nonblock(named_iofds
[fileno
], false);
598 return dup2(named_iofds
[fileno
], fileno
) < 0 ? -errno
: fileno
;
601 assert_not_reached("Unknown error type");
605 static int chown_terminal(int fd
, uid_t uid
) {
610 /* Before we chown/chmod the TTY, let's ensure this is actually a tty */
614 /* This might fail. What matters are the results. */
615 (void) fchown(fd
, uid
, -1);
616 (void) fchmod(fd
, TTY_MODE
);
618 if (fstat(fd
, &st
) < 0)
621 if (st
.st_uid
!= uid
|| (st
.st_mode
& 0777) != TTY_MODE
)
627 static int setup_confirm_stdio(int *_saved_stdin
, int *_saved_stdout
) {
628 _cleanup_close_
int fd
= -1, saved_stdin
= -1, saved_stdout
= -1;
631 assert(_saved_stdin
);
632 assert(_saved_stdout
);
634 saved_stdin
= fcntl(STDIN_FILENO
, F_DUPFD
, 3);
638 saved_stdout
= fcntl(STDOUT_FILENO
, F_DUPFD
, 3);
639 if (saved_stdout
< 0)
642 fd
= acquire_terminal(
647 DEFAULT_CONFIRM_USEC
);
651 r
= chown_terminal(fd
, getuid());
655 r
= reset_terminal_fd(fd
, true);
659 if (dup2(fd
, STDIN_FILENO
) < 0)
662 if (dup2(fd
, STDOUT_FILENO
) < 0)
669 *_saved_stdin
= saved_stdin
;
670 *_saved_stdout
= saved_stdout
;
672 saved_stdin
= saved_stdout
= -1;
677 _printf_(1, 2) static int write_confirm_message(const char *format
, ...) {
678 _cleanup_close_
int fd
= -1;
683 fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
687 va_start(ap
, format
);
688 vdprintf(fd
, format
, ap
);
694 static int restore_confirm_stdio(int *saved_stdin
, int *saved_stdout
) {
698 assert(saved_stdout
);
702 if (*saved_stdin
>= 0)
703 if (dup2(*saved_stdin
, STDIN_FILENO
) < 0)
706 if (*saved_stdout
>= 0)
707 if (dup2(*saved_stdout
, STDOUT_FILENO
) < 0)
710 *saved_stdin
= safe_close(*saved_stdin
);
711 *saved_stdout
= safe_close(*saved_stdout
);
716 static int ask_for_confirmation(char *response
, char **argv
) {
717 int saved_stdout
= -1, saved_stdin
= -1, r
;
718 _cleanup_free_
char *line
= NULL
;
720 r
= setup_confirm_stdio(&saved_stdin
, &saved_stdout
);
724 line
= exec_command_line(argv
);
728 r
= ask_char(response
, "yns", "Execute %s? [Yes, No, Skip] ", line
);
730 restore_confirm_stdio(&saved_stdin
, &saved_stdout
);
735 static int get_fixed_user(const ExecContext
*c
, const char **user
,
736 uid_t
*uid
, gid_t
*gid
,
737 const char **home
, const char **shell
) {
746 /* Note that we don't set $HOME or $SHELL if they are not particularly enlightening anyway
747 * (i.e. are "/" or "/bin/nologin"). */
750 r
= get_user_creds_clean(&name
, uid
, gid
, home
, shell
);
758 static int get_fixed_group(const ExecContext
*c
, const char **group
, gid_t
*gid
) {
768 r
= get_group_creds(&name
, gid
);
776 static int get_supplementary_groups(const ExecContext
*c
, const char *user
,
777 const char *group
, gid_t gid
,
778 gid_t
**supplementary_gids
, int *ngids
) {
782 bool keep_groups
= false;
783 gid_t
*groups
= NULL
;
784 _cleanup_free_ gid_t
*l_gids
= NULL
;
789 * If user is given, then lookup GID and supplementary groups list.
790 * We avoid NSS lookups for gid=0. Also we have to initialize groups
791 * here and as early as possible so we keep the list of supplementary
792 * groups of the caller.
794 if (user
&& gid_is_valid(gid
) && gid
!= 0) {
795 /* First step, initialize groups from /etc/groups */
796 if (initgroups(user
, gid
) < 0)
802 if (!c
->supplementary_groups
)
806 * If SupplementaryGroups= was passed then NGROUPS_MAX has to
807 * be positive, otherwise fail.
810 ngroups_max
= (int) sysconf(_SC_NGROUPS_MAX
);
811 if (ngroups_max
<= 0) {
815 return -EOPNOTSUPP
; /* For all other values */
818 l_gids
= new(gid_t
, ngroups_max
);
824 * Lookup the list of groups that the user belongs to, we
825 * avoid NSS lookups here too for gid=0.
828 if (getgrouplist(user
, gid
, l_gids
, &k
) < 0)
833 STRV_FOREACH(i
, c
->supplementary_groups
) {
836 if (k
>= ngroups_max
)
840 r
= get_group_creds(&g
, l_gids
+k
);
848 * Sets ngids to zero to drop all supplementary groups, happens
849 * when we are under root and SupplementaryGroups= is empty.
856 /* Otherwise get the final list of supplementary groups */
857 groups
= memdup(l_gids
, sizeof(gid_t
) * k
);
861 *supplementary_gids
= groups
;
869 static int enforce_groups(const ExecContext
*context
, gid_t gid
,
870 gid_t
*supplementary_gids
, int ngids
) {
875 /* Handle SupplementaryGroups= even if it is empty */
876 if (context
->supplementary_groups
) {
877 r
= maybe_setgroups(ngids
, supplementary_gids
);
882 if (gid_is_valid(gid
)) {
883 /* Then set our gids */
884 if (setresgid(gid
, gid
, gid
) < 0)
891 static int enforce_user(const ExecContext
*context
, uid_t uid
) {
894 if (!uid_is_valid(uid
))
897 /* Sets (but doesn't look up) the uid and make sure we keep the
898 * capabilities while doing so. */
900 if (context
->capability_ambient_set
!= 0) {
902 /* First step: If we need to keep capabilities but
903 * drop privileges we need to make sure we keep our
904 * caps, while we drop privileges. */
906 int sb
= context
->secure_bits
| 1<<SECURE_KEEP_CAPS
;
908 if (prctl(PR_GET_SECUREBITS
) != sb
)
909 if (prctl(PR_SET_SECUREBITS
, sb
) < 0)
914 /* Second step: actually set the uids */
915 if (setresuid(uid
, uid
, uid
) < 0)
918 /* At this point we should have all necessary capabilities but
919 are otherwise a normal user. However, the caps might got
920 corrupted due to the setresuid() so we need clean them up
921 later. This is done outside of this call. */
928 static int null_conv(
930 const struct pam_message
**msg
,
931 struct pam_response
**resp
,
934 /* We don't support conversations */
941 static int setup_pam(
948 int fds
[], unsigned n_fds
) {
952 static const struct pam_conv conv
= {
957 _cleanup_(barrier_destroy
) Barrier barrier
= BARRIER_NULL
;
958 pam_handle_t
*handle
= NULL
;
960 int pam_code
= PAM_SUCCESS
, r
;
961 char **nv
, **e
= NULL
;
962 bool close_session
= false;
963 pid_t pam_pid
= 0, parent_pid
;
970 /* We set up PAM in the parent process, then fork. The child
971 * will then stay around until killed via PR_GET_PDEATHSIG or
972 * systemd via the cgroup logic. It will then remove the PAM
973 * session again. The parent process will exec() the actual
974 * daemon. We do things this way to ensure that the main PID
975 * of the daemon is the one we initially fork()ed. */
977 r
= barrier_create(&barrier
);
981 if (log_get_max_level() < LOG_DEBUG
)
984 pam_code
= pam_start(name
, user
, &conv
, &handle
);
985 if (pam_code
!= PAM_SUCCESS
) {
991 pam_code
= pam_set_item(handle
, PAM_TTY
, tty
);
992 if (pam_code
!= PAM_SUCCESS
)
996 STRV_FOREACH(nv
, *env
) {
997 pam_code
= pam_putenv(handle
, *nv
);
998 if (pam_code
!= PAM_SUCCESS
)
1002 pam_code
= pam_acct_mgmt(handle
, flags
);
1003 if (pam_code
!= PAM_SUCCESS
)
1006 pam_code
= pam_open_session(handle
, flags
);
1007 if (pam_code
!= PAM_SUCCESS
)
1010 close_session
= true;
1012 e
= pam_getenvlist(handle
);
1014 pam_code
= PAM_BUF_ERR
;
1018 /* Block SIGTERM, so that we know that it won't get lost in
1021 assert_se(sigprocmask_many(SIG_BLOCK
, &old_ss
, SIGTERM
, -1) >= 0);
1023 parent_pid
= getpid();
1032 int sig
, ret
= EXIT_PAM
;
1034 /* The child's job is to reset the PAM session on
1036 barrier_set_role(&barrier
, BARRIER_CHILD
);
1038 /* This string must fit in 10 chars (i.e. the length
1039 * of "/sbin/init"), to look pretty in /bin/ps */
1040 rename_process("(sd-pam)");
1042 /* Make sure we don't keep open the passed fds in this
1043 child. We assume that otherwise only those fds are
1044 open here that have been opened by PAM. */
1045 close_many(fds
, n_fds
);
1047 /* Drop privileges - we don't need any to pam_close_session
1048 * and this will make PR_SET_PDEATHSIG work in most cases.
1049 * If this fails, ignore the error - but expect sd-pam threads
1050 * to fail to exit normally */
1052 r
= maybe_setgroups(0, NULL
);
1054 log_warning_errno(r
, "Failed to setgroups() in sd-pam: %m");
1055 if (setresgid(gid
, gid
, gid
) < 0)
1056 log_warning_errno(errno
, "Failed to setresgid() in sd-pam: %m");
1057 if (setresuid(uid
, uid
, uid
) < 0)
1058 log_warning_errno(errno
, "Failed to setresuid() in sd-pam: %m");
1060 (void) ignore_signals(SIGPIPE
, -1);
1062 /* Wait until our parent died. This will only work if
1063 * the above setresuid() succeeds, otherwise the kernel
1064 * will not allow unprivileged parents kill their privileged
1065 * children this way. We rely on the control groups kill logic
1066 * to do the rest for us. */
1067 if (prctl(PR_SET_PDEATHSIG
, SIGTERM
) < 0)
1070 /* Tell the parent that our setup is done. This is especially
1071 * important regarding dropping privileges. Otherwise, unit
1072 * setup might race against our setresuid(2) call. */
1073 barrier_place(&barrier
);
1075 /* Check if our parent process might already have
1077 if (getppid() == parent_pid
) {
1080 assert_se(sigemptyset(&ss
) >= 0);
1081 assert_se(sigaddset(&ss
, SIGTERM
) >= 0);
1084 if (sigwait(&ss
, &sig
) < 0) {
1091 assert(sig
== SIGTERM
);
1096 /* If our parent died we'll end the session */
1097 if (getppid() != parent_pid
) {
1098 pam_code
= pam_close_session(handle
, flags
);
1099 if (pam_code
!= PAM_SUCCESS
)
1106 pam_end(handle
, pam_code
| flags
);
1110 barrier_set_role(&barrier
, BARRIER_PARENT
);
1112 /* If the child was forked off successfully it will do all the
1113 * cleanups, so forget about the handle here. */
1116 /* Unblock SIGTERM again in the parent */
1117 assert_se(sigprocmask(SIG_SETMASK
, &old_ss
, NULL
) >= 0);
1119 /* We close the log explicitly here, since the PAM modules
1120 * might have opened it, but we don't want this fd around. */
1123 /* Synchronously wait for the child to initialize. We don't care for
1124 * errors as we cannot recover. However, warn loudly if it happens. */
1125 if (!barrier_place_and_sync(&barrier
))
1126 log_error("PAM initialization failed");
1134 if (pam_code
!= PAM_SUCCESS
) {
1135 log_error("PAM failed: %s", pam_strerror(handle
, pam_code
));
1136 r
= -EPERM
; /* PAM errors do not map to errno */
1138 log_error_errno(r
, "PAM failed: %m");
1142 pam_code
= pam_close_session(handle
, flags
);
1144 pam_end(handle
, pam_code
| flags
);
1156 static void rename_process_from_path(const char *path
) {
1157 char process_name
[11];
1161 /* This resulting string must fit in 10 chars (i.e. the length
1162 * of "/sbin/init") to look pretty in /bin/ps */
1166 rename_process("(...)");
1172 /* The end of the process name is usually more
1173 * interesting, since the first bit might just be
1179 process_name
[0] = '(';
1180 memcpy(process_name
+1, p
, l
);
1181 process_name
[1+l
] = ')';
1182 process_name
[1+l
+1] = 0;
1184 rename_process(process_name
);
1189 static bool skip_seccomp_unavailable(const Unit
* u
, const char* msg
) {
1191 if (is_seccomp_available())
1195 log_unit_debug(u
, "SECCOMP features not detected in the kernel, skipping %s", msg
);
1200 static int apply_seccomp(const Unit
* u
, const ExecContext
*c
) {
1201 uint32_t negative_action
, action
;
1202 scmp_filter_ctx seccomp
;
1209 if (skip_seccomp_unavailable(u
, "syscall filtering"))
1212 negative_action
= c
->syscall_errno
== 0 ? SCMP_ACT_KILL
: SCMP_ACT_ERRNO(c
->syscall_errno
);
1214 seccomp
= seccomp_init(c
->syscall_whitelist
? negative_action
: SCMP_ACT_ALLOW
);
1218 if (c
->syscall_archs
) {
1220 SET_FOREACH(id
, c
->syscall_archs
, i
) {
1221 r
= seccomp_arch_add(seccomp
, PTR_TO_UINT32(id
) - 1);
1229 r
= seccomp_add_secondary_archs(seccomp
);
1234 action
= c
->syscall_whitelist
? SCMP_ACT_ALLOW
: negative_action
;
1235 SET_FOREACH(id
, c
->syscall_filter
, i
) {
1236 r
= seccomp_rule_add(seccomp
, action
, PTR_TO_INT(id
) - 1, 0);
1241 r
= seccomp_attr_set(seccomp
, SCMP_FLTATR_CTL_NNP
, 0);
1245 r
= seccomp_load(seccomp
);
1248 seccomp_release(seccomp
);
1252 static int apply_address_families(const Unit
* u
, const ExecContext
*c
) {
1253 scmp_filter_ctx seccomp
;
1259 if (skip_seccomp_unavailable(u
, "RestrictAddressFamilies="))
1262 r
= seccomp_init_conservative(&seccomp
, SCMP_ACT_ALLOW
);
1266 if (c
->address_families_whitelist
) {
1267 int af
, first
= 0, last
= 0;
1270 /* If this is a whitelist, we first block the address
1271 * families that are out of range and then everything
1272 * that is not in the set. First, we find the lowest
1273 * and highest address family in the set. */
1275 SET_FOREACH(afp
, c
->address_families
, i
) {
1276 af
= PTR_TO_INT(afp
);
1278 if (af
<= 0 || af
>= af_max())
1281 if (first
== 0 || af
< first
)
1284 if (last
== 0 || af
> last
)
1288 assert((first
== 0) == (last
== 0));
1292 /* No entries in the valid range, block everything */
1293 r
= seccomp_rule_add(
1295 SCMP_ACT_ERRNO(EPROTONOSUPPORT
),
1303 /* Block everything below the first entry */
1304 r
= seccomp_rule_add(
1306 SCMP_ACT_ERRNO(EPROTONOSUPPORT
),
1309 SCMP_A0(SCMP_CMP_LT
, first
));
1313 /* Block everything above the last entry */
1314 r
= seccomp_rule_add(
1316 SCMP_ACT_ERRNO(EPROTONOSUPPORT
),
1319 SCMP_A0(SCMP_CMP_GT
, last
));
1323 /* Block everything between the first and last
1325 for (af
= 1; af
< af_max(); af
++) {
1327 if (set_contains(c
->address_families
, INT_TO_PTR(af
)))
1330 r
= seccomp_rule_add(
1332 SCMP_ACT_ERRNO(EPROTONOSUPPORT
),
1335 SCMP_A0(SCMP_CMP_EQ
, af
));
1344 /* If this is a blacklist, then generate one rule for
1345 * each address family that are then combined in OR
1348 SET_FOREACH(af
, c
->address_families
, i
) {
1350 r
= seccomp_rule_add(
1352 SCMP_ACT_ERRNO(EPROTONOSUPPORT
),
1355 SCMP_A0(SCMP_CMP_EQ
, PTR_TO_INT(af
)));
1361 r
= seccomp_load(seccomp
);
1364 seccomp_release(seccomp
);
1368 static int apply_memory_deny_write_execute(const Unit
* u
, const ExecContext
*c
) {
1369 scmp_filter_ctx seccomp
;
1374 if (skip_seccomp_unavailable(u
, "MemoryDenyWriteExecute="))
1377 r
= seccomp_init_conservative(&seccomp
, SCMP_ACT_ALLOW
);
1381 r
= seccomp_rule_add(
1383 SCMP_ACT_ERRNO(EPERM
),
1386 SCMP_A2(SCMP_CMP_MASKED_EQ
, PROT_EXEC
|PROT_WRITE
, PROT_EXEC
|PROT_WRITE
));
1390 r
= seccomp_rule_add(
1392 SCMP_ACT_ERRNO(EPERM
),
1395 SCMP_A2(SCMP_CMP_MASKED_EQ
, PROT_EXEC
, PROT_EXEC
));
1399 r
= seccomp_rule_add(
1401 SCMP_ACT_ERRNO(EPERM
),
1404 SCMP_A2(SCMP_CMP_MASKED_EQ
, SHM_EXEC
, SHM_EXEC
));
1408 r
= seccomp_load(seccomp
);
1411 seccomp_release(seccomp
);
1415 static int apply_restrict_realtime(const Unit
* u
, const ExecContext
*c
) {
1416 static const int permitted_policies
[] = {
1422 scmp_filter_ctx seccomp
;
1424 int r
, p
, max_policy
= 0;
1428 if (skip_seccomp_unavailable(u
, "RestrictRealtime="))
1431 r
= seccomp_init_conservative(&seccomp
, SCMP_ACT_ALLOW
);
1435 /* Determine the highest policy constant we want to allow */
1436 for (i
= 0; i
< ELEMENTSOF(permitted_policies
); i
++)
1437 if (permitted_policies
[i
] > max_policy
)
1438 max_policy
= permitted_policies
[i
];
1440 /* Go through all policies with lower values than that, and block them -- unless they appear in the
1442 for (p
= 0; p
< max_policy
; p
++) {
1445 /* Check if this is in the whitelist. */
1446 for (i
= 0; i
< ELEMENTSOF(permitted_policies
); i
++)
1447 if (permitted_policies
[i
] == p
) {
1455 /* Deny this policy */
1456 r
= seccomp_rule_add(
1458 SCMP_ACT_ERRNO(EPERM
),
1459 SCMP_SYS(sched_setscheduler
),
1461 SCMP_A1(SCMP_CMP_EQ
, p
));
1466 /* Blacklist all other policies, i.e. the ones with higher values. Note that all comparisons are unsigned here,
1467 * hence no need no check for < 0 values. */
1468 r
= seccomp_rule_add(
1470 SCMP_ACT_ERRNO(EPERM
),
1471 SCMP_SYS(sched_setscheduler
),
1473 SCMP_A1(SCMP_CMP_GT
, max_policy
));
1477 r
= seccomp_load(seccomp
);
1480 seccomp_release(seccomp
);
1484 static int apply_protect_sysctl(const Unit
*u
, const ExecContext
*c
) {
1485 scmp_filter_ctx seccomp
;
1490 /* Turn off the legacy sysctl() system call. Many distributions turn this off while building the kernel, but
1491 * let's protect even those systems where this is left on in the kernel. */
1493 if (skip_seccomp_unavailable(u
, "ProtectKernelTunables="))
1496 r
= seccomp_init_conservative(&seccomp
, SCMP_ACT_ALLOW
);
1500 r
= seccomp_rule_add(
1502 SCMP_ACT_ERRNO(EPERM
),
1508 r
= seccomp_load(seccomp
);
1511 seccomp_release(seccomp
);
1515 static int apply_protect_kernel_modules(const Unit
*u
, const ExecContext
*c
) {
1518 /* Turn off module syscalls on ProtectKernelModules=yes */
1520 if (skip_seccomp_unavailable(u
, "ProtectKernelModules="))
1523 return seccomp_load_filter_set(SCMP_ACT_ALLOW
, syscall_filter_sets
+ SYSCALL_FILTER_SET_MODULE
, SCMP_ACT_ERRNO(EPERM
));
1526 static int apply_private_devices(const Unit
*u
, const ExecContext
*c
) {
1529 /* If PrivateDevices= is set, also turn off iopl and all @raw-io syscalls. */
1531 if (skip_seccomp_unavailable(u
, "PrivateDevices="))
1534 return seccomp_load_filter_set(SCMP_ACT_ALLOW
, syscall_filter_sets
+ SYSCALL_FILTER_SET_RAW_IO
, SCMP_ACT_ERRNO(EPERM
));
1539 static void do_idle_pipe_dance(int idle_pipe
[4]) {
1542 idle_pipe
[1] = safe_close(idle_pipe
[1]);
1543 idle_pipe
[2] = safe_close(idle_pipe
[2]);
1545 if (idle_pipe
[0] >= 0) {
1548 r
= fd_wait_for_event(idle_pipe
[0], POLLHUP
, IDLE_TIMEOUT_USEC
);
1550 if (idle_pipe
[3] >= 0 && r
== 0 /* timeout */) {
1553 /* Signal systemd that we are bored and want to continue. */
1554 n
= write(idle_pipe
[3], "x", 1);
1556 /* Wait for systemd to react to the signal above. */
1557 fd_wait_for_event(idle_pipe
[0], POLLHUP
, IDLE_TIMEOUT2_USEC
);
1560 idle_pipe
[0] = safe_close(idle_pipe
[0]);
1564 idle_pipe
[3] = safe_close(idle_pipe
[3]);
1567 static int build_environment(
1569 const ExecContext
*c
,
1570 const ExecParameters
*p
,
1573 const char *username
,
1575 dev_t journal_stream_dev
,
1576 ino_t journal_stream_ino
,
1579 _cleanup_strv_free_
char **our_env
= NULL
;
1587 our_env
= new0(char*, 14);
1592 _cleanup_free_
char *joined
= NULL
;
1594 if (asprintf(&x
, "LISTEN_PID="PID_FMT
, getpid()) < 0)
1596 our_env
[n_env
++] = x
;
1598 if (asprintf(&x
, "LISTEN_FDS=%u", n_fds
) < 0)
1600 our_env
[n_env
++] = x
;
1602 joined
= strv_join(p
->fd_names
, ":");
1606 x
= strjoin("LISTEN_FDNAMES=", joined
, NULL
);
1609 our_env
[n_env
++] = x
;
1612 if ((p
->flags
& EXEC_SET_WATCHDOG
) && p
->watchdog_usec
> 0) {
1613 if (asprintf(&x
, "WATCHDOG_PID="PID_FMT
, getpid()) < 0)
1615 our_env
[n_env
++] = x
;
1617 if (asprintf(&x
, "WATCHDOG_USEC="USEC_FMT
, p
->watchdog_usec
) < 0)
1619 our_env
[n_env
++] = x
;
1622 /* If this is D-Bus, tell the nss-systemd module, since it relies on being able to use D-Bus look up dynamic
1623 * users via PID 1, possibly dead-locking the dbus daemon. This way it will not use D-Bus to resolve names, but
1624 * check the database directly. */
1625 if (unit_has_name(u
, SPECIAL_DBUS_SERVICE
)) {
1626 x
= strdup("SYSTEMD_NSS_BYPASS_BUS=1");
1629 our_env
[n_env
++] = x
;
1633 x
= strappend("HOME=", home
);
1636 our_env
[n_env
++] = x
;
1640 x
= strappend("LOGNAME=", username
);
1643 our_env
[n_env
++] = x
;
1645 x
= strappend("USER=", username
);
1648 our_env
[n_env
++] = x
;
1652 x
= strappend("SHELL=", shell
);
1655 our_env
[n_env
++] = x
;
1658 if (!sd_id128_is_null(u
->invocation_id
)) {
1659 if (asprintf(&x
, "INVOCATION_ID=" SD_ID128_FORMAT_STR
, SD_ID128_FORMAT_VAL(u
->invocation_id
)) < 0)
1662 our_env
[n_env
++] = x
;
1665 if (exec_context_needs_term(c
)) {
1666 const char *tty_path
, *term
= NULL
;
1668 tty_path
= exec_context_tty_path(c
);
1670 /* If we are forked off PID 1 and we are supposed to operate on /dev/console, then let's try to inherit
1671 * the $TERM set for PID 1. This is useful for containers so that the $TERM the container manager
1672 * passes to PID 1 ends up all the way in the console login shown. */
1674 if (path_equal(tty_path
, "/dev/console") && getppid() == 1)
1675 term
= getenv("TERM");
1677 term
= default_term_for_tty(tty_path
);
1679 x
= strappend("TERM=", term
);
1682 our_env
[n_env
++] = x
;
1685 if (journal_stream_dev
!= 0 && journal_stream_ino
!= 0) {
1686 if (asprintf(&x
, "JOURNAL_STREAM=" DEV_FMT
":" INO_FMT
, journal_stream_dev
, journal_stream_ino
) < 0)
1689 our_env
[n_env
++] = x
;
1692 our_env
[n_env
++] = NULL
;
1693 assert(n_env
<= 12);
1701 static int build_pass_environment(const ExecContext
*c
, char ***ret
) {
1702 _cleanup_strv_free_
char **pass_env
= NULL
;
1703 size_t n_env
= 0, n_bufsize
= 0;
1706 STRV_FOREACH(i
, c
->pass_environment
) {
1707 _cleanup_free_
char *x
= NULL
;
1713 x
= strjoin(*i
, "=", v
, NULL
);
1716 if (!GREEDY_REALLOC(pass_env
, n_bufsize
, n_env
+ 2))
1718 pass_env
[n_env
++] = x
;
1719 pass_env
[n_env
] = NULL
;
1729 static bool exec_needs_mount_namespace(
1730 const ExecContext
*context
,
1731 const ExecParameters
*params
,
1732 ExecRuntime
*runtime
) {
1737 if (!strv_isempty(context
->read_write_paths
) ||
1738 !strv_isempty(context
->read_only_paths
) ||
1739 !strv_isempty(context
->inaccessible_paths
))
1742 if (context
->mount_flags
!= 0)
1745 if (context
->private_tmp
&& runtime
&& (runtime
->tmp_dir
|| runtime
->var_tmp_dir
))
1748 if (context
->private_devices
||
1749 context
->protect_system
!= PROTECT_SYSTEM_NO
||
1750 context
->protect_home
!= PROTECT_HOME_NO
||
1751 context
->protect_kernel_tunables
||
1752 context
->protect_kernel_modules
||
1753 context
->protect_control_groups
)
1759 static int setup_private_users(uid_t uid
, gid_t gid
) {
1760 _cleanup_free_
char *uid_map
= NULL
, *gid_map
= NULL
;
1761 _cleanup_close_pair_
int errno_pipe
[2] = { -1, -1 };
1762 _cleanup_close_
int unshare_ready_fd
= -1;
1763 _cleanup_(sigkill_waitp
) pid_t pid
= 0;
1769 /* Set up a user namespace and map root to root, the selected UID/GID to itself, and everything else to
1770 * nobody. In order to be able to write this mapping we need CAP_SETUID in the original user namespace, which
1771 * we however lack after opening the user namespace. To work around this we fork() a temporary child process,
1772 * which waits for the parent to create the new user namespace while staying in the original namespace. The
1773 * child then writes the UID mapping, under full privileges. The parent waits for the child to finish and
1774 * continues execution normally. */
1776 if (uid
!= 0 && uid_is_valid(uid
))
1778 "0 0 1\n" /* Map root → root */
1779 UID_FMT
" " UID_FMT
" 1\n", /* Map $UID → $UID */
1782 uid_map
= strdup("0 0 1\n"); /* The case where the above is the same */
1786 if (gid
!= 0 && gid_is_valid(gid
))
1788 "0 0 1\n" /* Map root → root */
1789 GID_FMT
" " GID_FMT
" 1\n", /* Map $GID → $GID */
1792 gid_map
= strdup("0 0 1\n"); /* The case where the above is the same */
1796 /* Create a communication channel so that the parent can tell the child when it finished creating the user
1798 unshare_ready_fd
= eventfd(0, EFD_CLOEXEC
);
1799 if (unshare_ready_fd
< 0)
1802 /* Create a communication channel so that the child can tell the parent a proper error code in case it
1804 if (pipe2(errno_pipe
, O_CLOEXEC
) < 0)
1812 _cleanup_close_
int fd
= -1;
1816 /* Child process, running in the original user namespace. Let's update the parent's UID/GID map from
1817 * here, after the parent opened its own user namespace. */
1820 errno_pipe
[0] = safe_close(errno_pipe
[0]);
1822 /* Wait until the parent unshared the user namespace */
1823 if (read(unshare_ready_fd
, &c
, sizeof(c
)) < 0) {
1828 /* Disable the setgroups() system call in the child user namespace, for good. */
1829 a
= procfs_file_alloca(ppid
, "setgroups");
1830 fd
= open(a
, O_WRONLY
|O_CLOEXEC
);
1832 if (errno
!= ENOENT
) {
1837 /* If the file is missing the kernel is too old, let's continue anyway. */
1839 if (write(fd
, "deny\n", 5) < 0) {
1844 fd
= safe_close(fd
);
1847 /* First write the GID map */
1848 a
= procfs_file_alloca(ppid
, "gid_map");
1849 fd
= open(a
, O_WRONLY
|O_CLOEXEC
);
1854 if (write(fd
, gid_map
, strlen(gid_map
)) < 0) {
1858 fd
= safe_close(fd
);
1860 /* The write the UID map */
1861 a
= procfs_file_alloca(ppid
, "uid_map");
1862 fd
= open(a
, O_WRONLY
|O_CLOEXEC
);
1867 if (write(fd
, uid_map
, strlen(uid_map
)) < 0) {
1872 _exit(EXIT_SUCCESS
);
1875 (void) write(errno_pipe
[1], &r
, sizeof(r
));
1876 _exit(EXIT_FAILURE
);
1879 errno_pipe
[1] = safe_close(errno_pipe
[1]);
1881 if (unshare(CLONE_NEWUSER
) < 0)
1884 /* Let the child know that the namespace is ready now */
1885 if (write(unshare_ready_fd
, &c
, sizeof(c
)) < 0)
1888 /* Try to read an error code from the child */
1889 n
= read(errno_pipe
[0], &r
, sizeof(r
));
1892 if (n
== sizeof(r
)) { /* an error code was sent to us */
1897 if (n
!= 0) /* on success we should have read 0 bytes */
1900 r
= wait_for_terminate(pid
, &si
);
1905 /* If something strange happened with the child, let's consider this fatal, too */
1906 if (si
.si_code
!= CLD_EXITED
|| si
.si_status
!= 0)
1912 static int setup_runtime_directory(
1913 const ExecContext
*context
,
1914 const ExecParameters
*params
,
1924 STRV_FOREACH(rt
, context
->runtime_directory
) {
1925 _cleanup_free_
char *p
;
1927 p
= strjoin(params
->runtime_prefix
, "/", *rt
, NULL
);
1931 r
= mkdir_p_label(p
, context
->runtime_directory_mode
);
1935 r
= chmod_and_chown(p
, context
->runtime_directory_mode
, uid
, gid
);
1943 static int setup_smack(
1944 const ExecContext
*context
,
1945 const ExecCommand
*command
) {
1953 if (!mac_smack_use())
1956 if (context
->smack_process_label
) {
1957 r
= mac_smack_apply_pid(0, context
->smack_process_label
);
1961 #ifdef SMACK_DEFAULT_PROCESS_LABEL
1963 _cleanup_free_
char *exec_label
= NULL
;
1965 r
= mac_smack_read(command
->path
, SMACK_ATTR_EXEC
, &exec_label
);
1966 if (r
< 0 && r
!= -ENODATA
&& r
!= -EOPNOTSUPP
)
1969 r
= mac_smack_apply_pid(0, exec_label
? : SMACK_DEFAULT_PROCESS_LABEL
);
1979 static int compile_read_write_paths(
1980 const ExecContext
*context
,
1981 const ExecParameters
*params
,
1984 _cleanup_strv_free_
char **l
= NULL
;
1987 /* Compile the list of writable paths. This is the combination of the explicitly configured paths, plus all
1988 * runtime directories. */
1990 if (strv_isempty(context
->read_write_paths
) &&
1991 strv_isempty(context
->runtime_directory
)) {
1992 *ret
= NULL
; /* NOP if neither is set */
1996 l
= strv_copy(context
->read_write_paths
);
2000 STRV_FOREACH(rt
, context
->runtime_directory
) {
2003 s
= strjoin(params
->runtime_prefix
, "/", *rt
, NULL
);
2007 if (strv_consume(&l
, s
) < 0)
2017 static int apply_mount_namespace(Unit
*u
, const ExecContext
*context
,
2018 const ExecParameters
*params
,
2019 ExecRuntime
*runtime
) {
2021 _cleanup_free_
char **rw
= NULL
;
2022 char *tmp
= NULL
, *var
= NULL
;
2023 const char *root_dir
= NULL
;
2024 NameSpaceInfo ns_info
= {
2025 .private_dev
= context
->private_devices
,
2026 .protect_control_groups
= context
->protect_control_groups
,
2027 .protect_kernel_tunables
= context
->protect_kernel_tunables
,
2028 .protect_kernel_modules
= context
->protect_kernel_modules
,
2033 /* The runtime struct only contains the parent of the private /tmp,
2034 * which is non-accessible to world users. Inside of it there's a /tmp
2035 * that is sticky, and that's the one we want to use here. */
2037 if (context
->private_tmp
&& runtime
) {
2038 if (runtime
->tmp_dir
)
2039 tmp
= strjoina(runtime
->tmp_dir
, "/tmp");
2040 if (runtime
->var_tmp_dir
)
2041 var
= strjoina(runtime
->var_tmp_dir
, "/tmp");
2044 r
= compile_read_write_paths(context
, params
, &rw
);
2048 if (params
->flags
& EXEC_APPLY_CHROOT
)
2049 root_dir
= context
->root_directory
;
2051 r
= setup_namespace(root_dir
, &ns_info
, rw
,
2052 context
->read_only_paths
,
2053 context
->inaccessible_paths
,
2056 context
->protect_home
,
2057 context
->protect_system
,
2058 context
->mount_flags
);
2060 /* If we couldn't set up the namespace this is probably due to a
2061 * missing capability. In this case, silently proceeed. */
2062 if (IN_SET(r
, -EPERM
, -EACCES
)) {
2064 log_unit_debug_errno(u
, r
, "Failed to set up namespace, assuming containerized execution, ignoring: %m");
2072 static int apply_working_directory(const ExecContext
*context
,
2073 const ExecParameters
*params
,
2075 const bool needs_mount_ns
) {
2081 if (context
->working_directory_home
)
2083 else if (context
->working_directory
)
2084 wd
= context
->working_directory
;
2088 if (params
->flags
& EXEC_APPLY_CHROOT
) {
2089 if (!needs_mount_ns
&& context
->root_directory
)
2090 if (chroot(context
->root_directory
) < 0)
2095 d
= strjoina(strempty(context
->root_directory
), "/", strempty(wd
));
2097 if (chdir(d
) < 0 && !context
->working_directory_missing_ok
)
2103 static void append_socket_pair(int *array
, unsigned *n
, int pair
[2]) {
2111 array
[(*n
)++] = pair
[0];
2113 array
[(*n
)++] = pair
[1];
2116 static int close_remaining_fds(
2117 const ExecParameters
*params
,
2118 ExecRuntime
*runtime
,
2119 DynamicCreds
*dcreds
,
2122 int *fds
, unsigned n_fds
) {
2124 unsigned n_dont_close
= 0;
2125 int dont_close
[n_fds
+ 12];
2129 if (params
->stdin_fd
>= 0)
2130 dont_close
[n_dont_close
++] = params
->stdin_fd
;
2131 if (params
->stdout_fd
>= 0)
2132 dont_close
[n_dont_close
++] = params
->stdout_fd
;
2133 if (params
->stderr_fd
>= 0)
2134 dont_close
[n_dont_close
++] = params
->stderr_fd
;
2137 dont_close
[n_dont_close
++] = socket_fd
;
2139 memcpy(dont_close
+ n_dont_close
, fds
, sizeof(int) * n_fds
);
2140 n_dont_close
+= n_fds
;
2144 append_socket_pair(dont_close
, &n_dont_close
, runtime
->netns_storage_socket
);
2148 append_socket_pair(dont_close
, &n_dont_close
, dcreds
->user
->storage_socket
);
2150 append_socket_pair(dont_close
, &n_dont_close
, dcreds
->group
->storage_socket
);
2153 if (user_lookup_fd
>= 0)
2154 dont_close
[n_dont_close
++] = user_lookup_fd
;
2156 return close_all_fds(dont_close
, n_dont_close
);
2159 static bool context_has_address_families(const ExecContext
*c
) {
2162 return c
->address_families_whitelist
||
2163 !set_isempty(c
->address_families
);
2166 static bool context_has_syscall_filters(const ExecContext
*c
) {
2169 return c
->syscall_whitelist
||
2170 !set_isempty(c
->syscall_filter
) ||
2171 !set_isempty(c
->syscall_archs
);
2174 static bool context_has_no_new_privileges(const ExecContext
*c
) {
2177 if (c
->no_new_privileges
)
2180 if (have_effective_cap(CAP_SYS_ADMIN
)) /* if we are privileged, we don't need NNP */
2183 return context_has_address_families(c
) || /* we need NNP if we have any form of seccomp and are unprivileged */
2184 c
->memory_deny_write_execute
||
2185 c
->restrict_realtime
||
2186 c
->protect_kernel_tunables
||
2187 c
->protect_kernel_modules
||
2188 c
->private_devices
||
2189 context_has_syscall_filters(c
);
2192 static int send_user_lookup(
2200 /* Send the resolved UID/GID to PID 1 after we learnt it. We send a single datagram, containing the UID/GID
2201 * data as well as the unit name. Note that we suppress sending this if no user/group to resolve was
2204 if (user_lookup_fd
< 0)
2207 if (!uid_is_valid(uid
) && !gid_is_valid(gid
))
2210 if (writev(user_lookup_fd
,
2212 { .iov_base
= &uid
, .iov_len
= sizeof(uid
) },
2213 { .iov_base
= &gid
, .iov_len
= sizeof(gid
) },
2214 { .iov_base
= unit
->id
, .iov_len
= strlen(unit
->id
) }}, 3) < 0)
2220 static int exec_child(
2222 ExecCommand
*command
,
2223 const ExecContext
*context
,
2224 const ExecParameters
*params
,
2225 ExecRuntime
*runtime
,
2226 DynamicCreds
*dcreds
,
2230 int *fds
, unsigned n_fds
,
2235 _cleanup_strv_free_
char **our_env
= NULL
, **pass_env
= NULL
, **accum_env
= NULL
, **final_argv
= NULL
;
2236 _cleanup_free_
char *mac_selinux_context_net
= NULL
;
2237 _cleanup_free_ gid_t
*supplementary_gids
= NULL
;
2238 const char *username
= NULL
, *groupname
= NULL
;
2239 const char *home
= NULL
, *shell
= NULL
;
2240 dev_t journal_stream_dev
= 0;
2241 ino_t journal_stream_ino
= 0;
2242 bool needs_mount_namespace
;
2243 uid_t uid
= UID_INVALID
;
2244 gid_t gid
= GID_INVALID
;
2245 int i
, r
, ngids
= 0;
2251 assert(exit_status
);
2253 rename_process_from_path(command
->path
);
2255 /* We reset exactly these signals, since they are the
2256 * only ones we set to SIG_IGN in the main daemon. All
2257 * others we leave untouched because we set them to
2258 * SIG_DFL or a valid handler initially, both of which
2259 * will be demoted to SIG_DFL. */
2260 (void) default_signals(SIGNALS_CRASH_HANDLER
,
2261 SIGNALS_IGNORE
, -1);
2263 if (context
->ignore_sigpipe
)
2264 (void) ignore_signals(SIGPIPE
, -1);
2266 r
= reset_signal_mask();
2268 *exit_status
= EXIT_SIGNAL_MASK
;
2272 if (params
->idle_pipe
)
2273 do_idle_pipe_dance(params
->idle_pipe
);
2275 /* Close sockets very early to make sure we don't
2276 * block init reexecution because it cannot bind its
2281 r
= close_remaining_fds(params
, runtime
, dcreds
, user_lookup_fd
, socket_fd
, fds
, n_fds
);
2283 *exit_status
= EXIT_FDS
;
2287 if (!context
->same_pgrp
)
2289 *exit_status
= EXIT_SETSID
;
2293 exec_context_tty_reset(context
, params
);
2295 if (params
->flags
& EXEC_CONFIRM_SPAWN
) {
2298 r
= ask_for_confirmation(&response
, argv
);
2299 if (r
== -ETIMEDOUT
)
2300 write_confirm_message("Confirmation question timed out, assuming positive response.\n");
2302 write_confirm_message("Couldn't ask confirmation question, assuming positive response: %s\n", strerror(-r
));
2303 else if (response
== 's') {
2304 write_confirm_message("Skipping execution.\n");
2305 *exit_status
= EXIT_CONFIRM
;
2307 } else if (response
== 'n') {
2308 write_confirm_message("Failing execution.\n");
2314 if (context
->dynamic_user
&& dcreds
) {
2316 /* Make sure we bypass our own NSS module for any NSS checks */
2317 if (putenv((char*) "SYSTEMD_NSS_DYNAMIC_BYPASS=1") != 0) {
2318 *exit_status
= EXIT_USER
;
2322 r
= dynamic_creds_realize(dcreds
, &uid
, &gid
);
2324 *exit_status
= EXIT_USER
;
2328 if (!uid_is_valid(uid
) || !gid_is_valid(gid
)) {
2329 *exit_status
= EXIT_USER
;
2334 username
= dcreds
->user
->name
;
2337 r
= get_fixed_user(context
, &username
, &uid
, &gid
, &home
, &shell
);
2339 *exit_status
= EXIT_USER
;
2343 r
= get_fixed_group(context
, &groupname
, &gid
);
2345 *exit_status
= EXIT_GROUP
;
2350 /* Initialize user supplementary groups and get SupplementaryGroups= ones */
2351 r
= get_supplementary_groups(context
, username
, groupname
, gid
,
2352 &supplementary_gids
, &ngids
);
2354 *exit_status
= EXIT_GROUP
;
2358 r
= send_user_lookup(unit
, user_lookup_fd
, uid
, gid
);
2360 *exit_status
= EXIT_USER
;
2364 user_lookup_fd
= safe_close(user_lookup_fd
);
2366 /* If a socket is connected to STDIN/STDOUT/STDERR, we
2367 * must sure to drop O_NONBLOCK */
2369 (void) fd_nonblock(socket_fd
, false);
2371 r
= setup_input(context
, params
, socket_fd
, named_iofds
);
2373 *exit_status
= EXIT_STDIN
;
2377 r
= setup_output(unit
, context
, params
, STDOUT_FILENO
, socket_fd
, named_iofds
, basename(command
->path
), uid
, gid
, &journal_stream_dev
, &journal_stream_ino
);
2379 *exit_status
= EXIT_STDOUT
;
2383 r
= setup_output(unit
, context
, params
, STDERR_FILENO
, socket_fd
, named_iofds
, basename(command
->path
), uid
, gid
, &journal_stream_dev
, &journal_stream_ino
);
2385 *exit_status
= EXIT_STDERR
;
2389 if (params
->cgroup_path
) {
2390 r
= cg_attach_everywhere(params
->cgroup_supported
, params
->cgroup_path
, 0, NULL
, NULL
);
2392 *exit_status
= EXIT_CGROUP
;
2397 if (context
->oom_score_adjust_set
) {
2398 char t
[DECIMAL_STR_MAX(context
->oom_score_adjust
)];
2400 /* When we can't make this change due to EPERM, then
2401 * let's silently skip over it. User namespaces
2402 * prohibit write access to this file, and we
2403 * shouldn't trip up over that. */
2405 sprintf(t
, "%i", context
->oom_score_adjust
);
2406 r
= write_string_file("/proc/self/oom_score_adj", t
, 0);
2407 if (r
== -EPERM
|| r
== -EACCES
) {
2409 log_unit_debug_errno(unit
, r
, "Failed to adjust OOM setting, assuming containerized execution, ignoring: %m");
2412 *exit_status
= EXIT_OOM_ADJUST
;
2417 if (context
->nice_set
)
2418 if (setpriority(PRIO_PROCESS
, 0, context
->nice
) < 0) {
2419 *exit_status
= EXIT_NICE
;
2423 if (context
->cpu_sched_set
) {
2424 struct sched_param param
= {
2425 .sched_priority
= context
->cpu_sched_priority
,
2428 r
= sched_setscheduler(0,
2429 context
->cpu_sched_policy
|
2430 (context
->cpu_sched_reset_on_fork
?
2431 SCHED_RESET_ON_FORK
: 0),
2434 *exit_status
= EXIT_SETSCHEDULER
;
2439 if (context
->cpuset
)
2440 if (sched_setaffinity(0, CPU_ALLOC_SIZE(context
->cpuset_ncpus
), context
->cpuset
) < 0) {
2441 *exit_status
= EXIT_CPUAFFINITY
;
2445 if (context
->ioprio_set
)
2446 if (ioprio_set(IOPRIO_WHO_PROCESS
, 0, context
->ioprio
) < 0) {
2447 *exit_status
= EXIT_IOPRIO
;
2451 if (context
->timer_slack_nsec
!= NSEC_INFINITY
)
2452 if (prctl(PR_SET_TIMERSLACK
, context
->timer_slack_nsec
) < 0) {
2453 *exit_status
= EXIT_TIMERSLACK
;
2457 if (context
->personality
!= PERSONALITY_INVALID
)
2458 if (personality(context
->personality
) < 0) {
2459 *exit_status
= EXIT_PERSONALITY
;
2463 if (context
->utmp_id
)
2464 utmp_put_init_process(context
->utmp_id
, getpid(), getsid(0), context
->tty_path
,
2465 context
->utmp_mode
== EXEC_UTMP_INIT
? INIT_PROCESS
:
2466 context
->utmp_mode
== EXEC_UTMP_LOGIN
? LOGIN_PROCESS
:
2468 username
? "root" : context
->user
);
2470 if (context
->user
) {
2471 r
= chown_terminal(STDIN_FILENO
, uid
);
2473 *exit_status
= EXIT_STDIN
;
2478 /* If delegation is enabled we'll pass ownership of the cgroup
2479 * (but only in systemd's own controller hierarchy!) to the
2480 * user of the new process. */
2481 if (params
->cgroup_path
&& context
->user
&& params
->cgroup_delegate
) {
2482 r
= cg_set_task_access(SYSTEMD_CGROUP_CONTROLLER
, params
->cgroup_path
, 0644, uid
, gid
);
2484 *exit_status
= EXIT_CGROUP
;
2489 r
= cg_set_group_access(SYSTEMD_CGROUP_CONTROLLER
, params
->cgroup_path
, 0755, uid
, gid
);
2491 *exit_status
= EXIT_CGROUP
;
2496 if (!strv_isempty(context
->runtime_directory
) && params
->runtime_prefix
) {
2497 r
= setup_runtime_directory(context
, params
, uid
, gid
);
2499 *exit_status
= EXIT_RUNTIME_DIRECTORY
;
2504 r
= build_environment(
2516 *exit_status
= EXIT_MEMORY
;
2520 r
= build_pass_environment(context
, &pass_env
);
2522 *exit_status
= EXIT_MEMORY
;
2526 accum_env
= strv_env_merge(5,
2527 params
->environment
,
2530 context
->environment
,
2534 *exit_status
= EXIT_MEMORY
;
2537 accum_env
= strv_env_clean(accum_env
);
2539 (void) umask(context
->umask
);
2541 if ((params
->flags
& EXEC_APPLY_PERMISSIONS
) && !command
->privileged
) {
2542 if (context
->pam_name
&& username
) {
2543 r
= setup_pam(context
->pam_name
, username
, uid
, gid
, context
->tty_path
, &accum_env
, fds
, n_fds
);
2545 *exit_status
= EXIT_PAM
;
2551 if (context
->private_network
&& runtime
&& runtime
->netns_storage_socket
[0] >= 0) {
2552 r
= setup_netns(runtime
->netns_storage_socket
);
2554 *exit_status
= EXIT_NETWORK
;
2559 needs_mount_namespace
= exec_needs_mount_namespace(context
, params
, runtime
);
2560 if (needs_mount_namespace
) {
2561 r
= apply_mount_namespace(unit
, context
, params
, runtime
);
2563 *exit_status
= EXIT_NAMESPACE
;
2568 /* Apply just after mount namespace setup */
2569 r
= apply_working_directory(context
, params
, home
, needs_mount_namespace
);
2571 *exit_status
= EXIT_CHROOT
;
2575 /* Drop groups as early as possbile */
2576 if ((params
->flags
& EXEC_APPLY_PERMISSIONS
) && !command
->privileged
) {
2577 r
= enforce_groups(context
, gid
, supplementary_gids
, ngids
);
2579 *exit_status
= EXIT_GROUP
;
2585 if ((params
->flags
& EXEC_APPLY_PERMISSIONS
) &&
2586 mac_selinux_use() &&
2587 params
->selinux_context_net
&&
2589 !command
->privileged
) {
2591 r
= mac_selinux_get_child_mls_label(socket_fd
, command
->path
, context
->selinux_context
, &mac_selinux_context_net
);
2593 *exit_status
= EXIT_SELINUX_CONTEXT
;
2599 if ((params
->flags
& EXEC_APPLY_PERMISSIONS
) && context
->private_users
) {
2600 r
= setup_private_users(uid
, gid
);
2602 *exit_status
= EXIT_USER
;
2607 /* We repeat the fd closing here, to make sure that
2608 * nothing is leaked from the PAM modules. Note that
2609 * we are more aggressive this time since socket_fd
2610 * and the netns fds we don't need anymore. The custom
2611 * endpoint fd was needed to upload the policy and can
2612 * now be closed as well. */
2613 r
= close_all_fds(fds
, n_fds
);
2615 r
= shift_fds(fds
, n_fds
);
2617 r
= flags_fds(fds
, n_fds
, context
->non_blocking
);
2619 *exit_status
= EXIT_FDS
;
2623 if ((params
->flags
& EXEC_APPLY_PERMISSIONS
) && !command
->privileged
) {
2625 int secure_bits
= context
->secure_bits
;
2627 for (i
= 0; i
< _RLIMIT_MAX
; i
++) {
2629 if (!context
->rlimit
[i
])
2632 r
= setrlimit_closest(i
, context
->rlimit
[i
]);
2634 *exit_status
= EXIT_LIMITS
;
2639 /* Set the RTPRIO resource limit to 0, but only if nothing else was explicitly requested. */
2640 if (context
->restrict_realtime
&& !context
->rlimit
[RLIMIT_RTPRIO
]) {
2641 if (setrlimit(RLIMIT_RTPRIO
, &RLIMIT_MAKE_CONST(0)) < 0) {
2642 *exit_status
= EXIT_LIMITS
;
2647 if (!cap_test_all(context
->capability_bounding_set
)) {
2648 r
= capability_bounding_set_drop(context
->capability_bounding_set
, false);
2650 *exit_status
= EXIT_CAPABILITIES
;
2655 /* This is done before enforce_user, but ambient set
2656 * does not survive over setresuid() if keep_caps is not set. */
2657 if (context
->capability_ambient_set
!= 0) {
2658 r
= capability_ambient_set_apply(context
->capability_ambient_set
, true);
2660 *exit_status
= EXIT_CAPABILITIES
;
2665 if (context
->user
) {
2666 r
= enforce_user(context
, uid
);
2668 *exit_status
= EXIT_USER
;
2671 if (context
->capability_ambient_set
!= 0) {
2673 /* Fix the ambient capabilities after user change. */
2674 r
= capability_ambient_set_apply(context
->capability_ambient_set
, false);
2676 *exit_status
= EXIT_CAPABILITIES
;
2680 /* If we were asked to change user and ambient capabilities
2681 * were requested, we had to add keep-caps to the securebits
2682 * so that we would maintain the inherited capability set
2683 * through the setresuid(). Make sure that the bit is added
2684 * also to the context secure_bits so that we don't try to
2685 * drop the bit away next. */
2687 secure_bits
|= 1<<SECURE_KEEP_CAPS
;
2691 /* Apply the MAC contexts late, but before seccomp syscall filtering, as those should really be last to
2692 * influence our own codepaths as little as possible. Moreover, applying MAC contexts usually requires
2693 * syscalls that are subject to seccomp filtering, hence should probably be applied before the syscalls
2694 * are restricted. */
2697 if (mac_selinux_use()) {
2698 char *exec_context
= mac_selinux_context_net
?: context
->selinux_context
;
2701 r
= setexeccon(exec_context
);
2703 *exit_status
= EXIT_SELINUX_CONTEXT
;
2710 r
= setup_smack(context
, command
);
2712 *exit_status
= EXIT_SMACK_PROCESS_LABEL
;
2716 #ifdef HAVE_APPARMOR
2717 if (context
->apparmor_profile
&& mac_apparmor_use()) {
2718 r
= aa_change_onexec(context
->apparmor_profile
);
2719 if (r
< 0 && !context
->apparmor_profile_ignore
) {
2720 *exit_status
= EXIT_APPARMOR_PROFILE
;
2726 /* PR_GET_SECUREBITS is not privileged, while
2727 * PR_SET_SECUREBITS is. So to suppress
2728 * potential EPERMs we'll try not to call
2729 * PR_SET_SECUREBITS unless necessary. */
2730 if (prctl(PR_GET_SECUREBITS
) != secure_bits
)
2731 if (prctl(PR_SET_SECUREBITS
, secure_bits
) < 0) {
2732 *exit_status
= EXIT_SECUREBITS
;
2736 if (context_has_no_new_privileges(context
))
2737 if (prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0) < 0) {
2738 *exit_status
= EXIT_NO_NEW_PRIVILEGES
;
2743 if (context_has_address_families(context
)) {
2744 r
= apply_address_families(unit
, context
);
2746 *exit_status
= EXIT_ADDRESS_FAMILIES
;
2751 if (context
->memory_deny_write_execute
) {
2752 r
= apply_memory_deny_write_execute(unit
, context
);
2754 *exit_status
= EXIT_SECCOMP
;
2759 if (context
->restrict_realtime
) {
2760 r
= apply_restrict_realtime(unit
, context
);
2762 *exit_status
= EXIT_SECCOMP
;
2767 if (context
->protect_kernel_tunables
) {
2768 r
= apply_protect_sysctl(unit
, context
);
2770 *exit_status
= EXIT_SECCOMP
;
2775 if (context
->protect_kernel_modules
) {
2776 r
= apply_protect_kernel_modules(unit
, context
);
2778 *exit_status
= EXIT_SECCOMP
;
2783 if (context
->private_devices
) {
2784 r
= apply_private_devices(unit
, context
);
2786 *exit_status
= EXIT_SECCOMP
;
2791 /* This really should remain the last step before the execve(), to make sure our own code is unaffected
2792 * by the filter as little as possible. */
2793 if (context_has_syscall_filters(context
)) {
2794 r
= apply_seccomp(unit
, context
);
2796 *exit_status
= EXIT_SECCOMP
;
2803 final_argv
= replace_env_argv(argv
, accum_env
);
2805 *exit_status
= EXIT_MEMORY
;
2809 if (_unlikely_(log_get_max_level() >= LOG_DEBUG
)) {
2810 _cleanup_free_
char *line
;
2812 line
= exec_command_line(final_argv
);
2815 log_struct(LOG_DEBUG
,
2817 "EXECUTABLE=%s", command
->path
,
2818 LOG_UNIT_MESSAGE(unit
, "Executing: %s", line
),
2824 execve(command
->path
, final_argv
, accum_env
);
2825 *exit_status
= EXIT_EXEC
;
2829 int exec_spawn(Unit
*unit
,
2830 ExecCommand
*command
,
2831 const ExecContext
*context
,
2832 const ExecParameters
*params
,
2833 ExecRuntime
*runtime
,
2834 DynamicCreds
*dcreds
,
2837 _cleanup_strv_free_
char **files_env
= NULL
;
2838 int *fds
= NULL
; unsigned n_fds
= 0;
2839 _cleanup_free_
char *line
= NULL
;
2841 int named_iofds
[3] = { -1, -1, -1 };
2850 assert(params
->fds
|| params
->n_fds
<= 0);
2852 if (context
->std_input
== EXEC_INPUT_SOCKET
||
2853 context
->std_output
== EXEC_OUTPUT_SOCKET
||
2854 context
->std_error
== EXEC_OUTPUT_SOCKET
) {
2856 if (params
->n_fds
!= 1) {
2857 log_unit_error(unit
, "Got more than one socket.");
2861 socket_fd
= params
->fds
[0];
2865 n_fds
= params
->n_fds
;
2868 r
= exec_context_named_iofds(unit
, context
, params
, named_iofds
);
2870 return log_unit_error_errno(unit
, r
, "Failed to load a named file descriptor: %m");
2872 r
= exec_context_load_environment(unit
, context
, &files_env
);
2874 return log_unit_error_errno(unit
, r
, "Failed to load environment files: %m");
2876 argv
= params
->argv
?: command
->argv
;
2877 line
= exec_command_line(argv
);
2881 log_struct(LOG_DEBUG
,
2883 LOG_UNIT_MESSAGE(unit
, "About to execute: %s", line
),
2884 "EXECUTABLE=%s", command
->path
,
2888 return log_unit_error_errno(unit
, errno
, "Failed to fork: %m");
2893 r
= exec_child(unit
,
2904 unit
->manager
->user_lookup_fds
[1],
2908 log_struct_errno(LOG_ERR
, r
,
2909 LOG_MESSAGE_ID(SD_MESSAGE_SPAWN_FAILED
),
2911 LOG_UNIT_MESSAGE(unit
, "Failed at step %s spawning %s: %m",
2912 exit_status_to_string(exit_status
, EXIT_STATUS_SYSTEMD
),
2914 "EXECUTABLE=%s", command
->path
,
2921 log_unit_debug(unit
, "Forked %s as "PID_FMT
, command
->path
, pid
);
2923 /* We add the new process to the cgroup both in the child (so
2924 * that we can be sure that no user code is ever executed
2925 * outside of the cgroup) and in the parent (so that we can be
2926 * sure that when we kill the cgroup the process will be
2928 if (params
->cgroup_path
)
2929 (void) cg_attach(SYSTEMD_CGROUP_CONTROLLER
, params
->cgroup_path
, pid
);
2931 exec_status_start(&command
->exec_status
, pid
);
2937 void exec_context_init(ExecContext
*c
) {
2941 c
->ioprio
= IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE
, 0);
2942 c
->cpu_sched_policy
= SCHED_OTHER
;
2943 c
->syslog_priority
= LOG_DAEMON
|LOG_INFO
;
2944 c
->syslog_level_prefix
= true;
2945 c
->ignore_sigpipe
= true;
2946 c
->timer_slack_nsec
= NSEC_INFINITY
;
2947 c
->personality
= PERSONALITY_INVALID
;
2948 c
->runtime_directory_mode
= 0755;
2949 c
->capability_bounding_set
= CAP_ALL
;
2952 void exec_context_done(ExecContext
*c
) {
2957 c
->environment
= strv_free(c
->environment
);
2958 c
->environment_files
= strv_free(c
->environment_files
);
2959 c
->pass_environment
= strv_free(c
->pass_environment
);
2961 for (l
= 0; l
< ELEMENTSOF(c
->rlimit
); l
++)
2962 c
->rlimit
[l
] = mfree(c
->rlimit
[l
]);
2964 for (l
= 0; l
< 3; l
++)
2965 c
->stdio_fdname
[l
] = mfree(c
->stdio_fdname
[l
]);
2967 c
->working_directory
= mfree(c
->working_directory
);
2968 c
->root_directory
= mfree(c
->root_directory
);
2969 c
->tty_path
= mfree(c
->tty_path
);
2970 c
->syslog_identifier
= mfree(c
->syslog_identifier
);
2971 c
->user
= mfree(c
->user
);
2972 c
->group
= mfree(c
->group
);
2974 c
->supplementary_groups
= strv_free(c
->supplementary_groups
);
2976 c
->pam_name
= mfree(c
->pam_name
);
2978 c
->read_only_paths
= strv_free(c
->read_only_paths
);
2979 c
->read_write_paths
= strv_free(c
->read_write_paths
);
2980 c
->inaccessible_paths
= strv_free(c
->inaccessible_paths
);
2983 CPU_FREE(c
->cpuset
);
2985 c
->utmp_id
= mfree(c
->utmp_id
);
2986 c
->selinux_context
= mfree(c
->selinux_context
);
2987 c
->apparmor_profile
= mfree(c
->apparmor_profile
);
2989 c
->syscall_filter
= set_free(c
->syscall_filter
);
2990 c
->syscall_archs
= set_free(c
->syscall_archs
);
2991 c
->address_families
= set_free(c
->address_families
);
2993 c
->runtime_directory
= strv_free(c
->runtime_directory
);
2996 int exec_context_destroy_runtime_directory(ExecContext
*c
, const char *runtime_prefix
) {
3001 if (!runtime_prefix
)
3004 STRV_FOREACH(i
, c
->runtime_directory
) {
3005 _cleanup_free_
char *p
;
3007 p
= strjoin(runtime_prefix
, "/", *i
, NULL
);
3011 /* We execute this synchronously, since we need to be
3012 * sure this is gone when we start the service
3014 (void) rm_rf(p
, REMOVE_ROOT
);
3020 void exec_command_done(ExecCommand
*c
) {
3023 c
->path
= mfree(c
->path
);
3025 c
->argv
= strv_free(c
->argv
);
3028 void exec_command_done_array(ExecCommand
*c
, unsigned n
) {
3031 for (i
= 0; i
< n
; i
++)
3032 exec_command_done(c
+i
);
3035 ExecCommand
* exec_command_free_list(ExecCommand
*c
) {
3039 LIST_REMOVE(command
, c
, i
);
3040 exec_command_done(i
);
3047 void exec_command_free_array(ExecCommand
**c
, unsigned n
) {
3050 for (i
= 0; i
< n
; i
++)
3051 c
[i
] = exec_command_free_list(c
[i
]);
3054 typedef struct InvalidEnvInfo
{
3059 static void invalid_env(const char *p
, void *userdata
) {
3060 InvalidEnvInfo
*info
= userdata
;
3062 log_unit_error(info
->unit
, "Ignoring invalid environment assignment '%s': %s", p
, info
->path
);
3065 const char* exec_context_fdname(const ExecContext
*c
, int fd_index
) {
3070 if (c
->std_input
!= EXEC_INPUT_NAMED_FD
)
3072 return c
->stdio_fdname
[STDIN_FILENO
] ?: "stdin";
3074 if (c
->std_output
!= EXEC_OUTPUT_NAMED_FD
)
3076 return c
->stdio_fdname
[STDOUT_FILENO
] ?: "stdout";
3078 if (c
->std_error
!= EXEC_OUTPUT_NAMED_FD
)
3080 return c
->stdio_fdname
[STDERR_FILENO
] ?: "stderr";
3086 int exec_context_named_iofds(Unit
*unit
, const ExecContext
*c
, const ExecParameters
*p
, int named_iofds
[3]) {
3087 unsigned i
, targets
;
3088 const char *stdio_fdname
[3];
3093 targets
= (c
->std_input
== EXEC_INPUT_NAMED_FD
) +
3094 (c
->std_output
== EXEC_OUTPUT_NAMED_FD
) +
3095 (c
->std_error
== EXEC_OUTPUT_NAMED_FD
);
3097 for (i
= 0; i
< 3; i
++)
3098 stdio_fdname
[i
] = exec_context_fdname(c
, i
);
3100 for (i
= 0; i
< p
->n_fds
&& targets
> 0; i
++)
3101 if (named_iofds
[STDIN_FILENO
] < 0 && c
->std_input
== EXEC_INPUT_NAMED_FD
&& stdio_fdname
[STDIN_FILENO
] && streq(p
->fd_names
[i
], stdio_fdname
[STDIN_FILENO
])) {
3102 named_iofds
[STDIN_FILENO
] = p
->fds
[i
];
3104 } else if (named_iofds
[STDOUT_FILENO
] < 0 && c
->std_output
== EXEC_OUTPUT_NAMED_FD
&& stdio_fdname
[STDOUT_FILENO
] && streq(p
->fd_names
[i
], stdio_fdname
[STDOUT_FILENO
])) {
3105 named_iofds
[STDOUT_FILENO
] = p
->fds
[i
];
3107 } else if (named_iofds
[STDERR_FILENO
] < 0 && c
->std_error
== EXEC_OUTPUT_NAMED_FD
&& stdio_fdname
[STDERR_FILENO
] && streq(p
->fd_names
[i
], stdio_fdname
[STDERR_FILENO
])) {
3108 named_iofds
[STDERR_FILENO
] = p
->fds
[i
];
3112 return (targets
== 0 ? 0 : -ENOENT
);
3115 int exec_context_load_environment(Unit
*unit
, const ExecContext
*c
, char ***l
) {
3116 char **i
, **r
= NULL
;
3121 STRV_FOREACH(i
, c
->environment_files
) {
3124 bool ignore
= false;
3126 _cleanup_globfree_ glob_t pglob
= {};
3136 if (!path_is_absolute(fn
)) {
3144 /* Filename supports globbing, take all matching files */
3146 if (glob(fn
, 0, NULL
, &pglob
) != 0) {
3151 return errno
> 0 ? -errno
: -EINVAL
;
3153 count
= pglob
.gl_pathc
;
3161 for (n
= 0; n
< count
; n
++) {
3162 k
= load_env_file(NULL
, pglob
.gl_pathv
[n
], NULL
, &p
);
3170 /* Log invalid environment variables with filename */
3172 InvalidEnvInfo info
= {
3174 .path
= pglob
.gl_pathv
[n
]
3177 p
= strv_env_clean_with_callback(p
, invalid_env
, &info
);
3185 m
= strv_env_merge(2, r
, p
);
3201 static bool tty_may_match_dev_console(const char *tty
) {
3202 _cleanup_free_
char *active
= NULL
;
3208 if (startswith(tty
, "/dev/"))
3211 /* trivial identity? */
3212 if (streq(tty
, "console"))
3215 console
= resolve_dev_console(&active
);
3216 /* if we could not resolve, assume it may */
3220 /* "tty0" means the active VC, so it may be the same sometimes */
3221 return streq(console
, tty
) || (streq(console
, "tty0") && tty_is_vc(tty
));
3224 bool exec_context_may_touch_console(ExecContext
*ec
) {
3226 return (ec
->tty_reset
||
3228 ec
->tty_vt_disallocate
||
3229 is_terminal_input(ec
->std_input
) ||
3230 is_terminal_output(ec
->std_output
) ||
3231 is_terminal_output(ec
->std_error
)) &&
3232 tty_may_match_dev_console(exec_context_tty_path(ec
));
3235 static void strv_fprintf(FILE *f
, char **l
) {
3241 fprintf(f
, " %s", *g
);
3244 void exec_context_dump(ExecContext
*c
, FILE* f
, const char *prefix
) {
3251 prefix
= strempty(prefix
);
3255 "%sWorkingDirectory: %s\n"
3256 "%sRootDirectory: %s\n"
3257 "%sNonBlocking: %s\n"
3258 "%sPrivateTmp: %s\n"
3259 "%sPrivateDevices: %s\n"
3260 "%sProtectKernelTunables: %s\n"
3261 "%sProtectKernelModules: %s\n"
3262 "%sProtectControlGroups: %s\n"
3263 "%sPrivateNetwork: %s\n"
3264 "%sPrivateUsers: %s\n"
3265 "%sProtectHome: %s\n"
3266 "%sProtectSystem: %s\n"
3267 "%sIgnoreSIGPIPE: %s\n"
3268 "%sMemoryDenyWriteExecute: %s\n"
3269 "%sRestrictRealtime: %s\n",
3271 prefix
, c
->working_directory
? c
->working_directory
: "/",
3272 prefix
, c
->root_directory
? c
->root_directory
: "/",
3273 prefix
, yes_no(c
->non_blocking
),
3274 prefix
, yes_no(c
->private_tmp
),
3275 prefix
, yes_no(c
->private_devices
),
3276 prefix
, yes_no(c
->protect_kernel_tunables
),
3277 prefix
, yes_no(c
->protect_kernel_modules
),
3278 prefix
, yes_no(c
->protect_control_groups
),
3279 prefix
, yes_no(c
->private_network
),
3280 prefix
, yes_no(c
->private_users
),
3281 prefix
, protect_home_to_string(c
->protect_home
),
3282 prefix
, protect_system_to_string(c
->protect_system
),
3283 prefix
, yes_no(c
->ignore_sigpipe
),
3284 prefix
, yes_no(c
->memory_deny_write_execute
),
3285 prefix
, yes_no(c
->restrict_realtime
));
3287 STRV_FOREACH(e
, c
->environment
)
3288 fprintf(f
, "%sEnvironment: %s\n", prefix
, *e
);
3290 STRV_FOREACH(e
, c
->environment_files
)
3291 fprintf(f
, "%sEnvironmentFile: %s\n", prefix
, *e
);
3293 STRV_FOREACH(e
, c
->pass_environment
)
3294 fprintf(f
, "%sPassEnvironment: %s\n", prefix
, *e
);
3296 fprintf(f
, "%sRuntimeDirectoryMode: %04o\n", prefix
, c
->runtime_directory_mode
);
3298 STRV_FOREACH(d
, c
->runtime_directory
)
3299 fprintf(f
, "%sRuntimeDirectory: %s\n", prefix
, *d
);
3306 if (c
->oom_score_adjust_set
)
3308 "%sOOMScoreAdjust: %i\n",
3309 prefix
, c
->oom_score_adjust
);
3311 for (i
= 0; i
< RLIM_NLIMITS
; i
++)
3313 fprintf(f
, "%s%s: " RLIM_FMT
"\n",
3314 prefix
, rlimit_to_string(i
), c
->rlimit
[i
]->rlim_max
);
3315 fprintf(f
, "%s%sSoft: " RLIM_FMT
"\n",
3316 prefix
, rlimit_to_string(i
), c
->rlimit
[i
]->rlim_cur
);
3319 if (c
->ioprio_set
) {
3320 _cleanup_free_
char *class_str
= NULL
;
3322 ioprio_class_to_string_alloc(IOPRIO_PRIO_CLASS(c
->ioprio
), &class_str
);
3324 "%sIOSchedulingClass: %s\n"
3325 "%sIOPriority: %i\n",
3326 prefix
, strna(class_str
),
3327 prefix
, (int) IOPRIO_PRIO_DATA(c
->ioprio
));
3330 if (c
->cpu_sched_set
) {
3331 _cleanup_free_
char *policy_str
= NULL
;
3333 sched_policy_to_string_alloc(c
->cpu_sched_policy
, &policy_str
);
3335 "%sCPUSchedulingPolicy: %s\n"
3336 "%sCPUSchedulingPriority: %i\n"
3337 "%sCPUSchedulingResetOnFork: %s\n",
3338 prefix
, strna(policy_str
),
3339 prefix
, c
->cpu_sched_priority
,
3340 prefix
, yes_no(c
->cpu_sched_reset_on_fork
));
3344 fprintf(f
, "%sCPUAffinity:", prefix
);
3345 for (i
= 0; i
< c
->cpuset_ncpus
; i
++)
3346 if (CPU_ISSET_S(i
, CPU_ALLOC_SIZE(c
->cpuset_ncpus
), c
->cpuset
))
3347 fprintf(f
, " %u", i
);
3351 if (c
->timer_slack_nsec
!= NSEC_INFINITY
)
3352 fprintf(f
, "%sTimerSlackNSec: "NSEC_FMT
"\n", prefix
, c
->timer_slack_nsec
);
3355 "%sStandardInput: %s\n"
3356 "%sStandardOutput: %s\n"
3357 "%sStandardError: %s\n",
3358 prefix
, exec_input_to_string(c
->std_input
),
3359 prefix
, exec_output_to_string(c
->std_output
),
3360 prefix
, exec_output_to_string(c
->std_error
));
3366 "%sTTYVHangup: %s\n"
3367 "%sTTYVTDisallocate: %s\n",
3368 prefix
, c
->tty_path
,
3369 prefix
, yes_no(c
->tty_reset
),
3370 prefix
, yes_no(c
->tty_vhangup
),
3371 prefix
, yes_no(c
->tty_vt_disallocate
));
3373 if (c
->std_output
== EXEC_OUTPUT_SYSLOG
||
3374 c
->std_output
== EXEC_OUTPUT_KMSG
||
3375 c
->std_output
== EXEC_OUTPUT_JOURNAL
||
3376 c
->std_output
== EXEC_OUTPUT_SYSLOG_AND_CONSOLE
||
3377 c
->std_output
== EXEC_OUTPUT_KMSG_AND_CONSOLE
||
3378 c
->std_output
== EXEC_OUTPUT_JOURNAL_AND_CONSOLE
||
3379 c
->std_error
== EXEC_OUTPUT_SYSLOG
||
3380 c
->std_error
== EXEC_OUTPUT_KMSG
||
3381 c
->std_error
== EXEC_OUTPUT_JOURNAL
||
3382 c
->std_error
== EXEC_OUTPUT_SYSLOG_AND_CONSOLE
||
3383 c
->std_error
== EXEC_OUTPUT_KMSG_AND_CONSOLE
||
3384 c
->std_error
== EXEC_OUTPUT_JOURNAL_AND_CONSOLE
) {
3386 _cleanup_free_
char *fac_str
= NULL
, *lvl_str
= NULL
;
3388 log_facility_unshifted_to_string_alloc(c
->syslog_priority
>> 3, &fac_str
);
3389 log_level_to_string_alloc(LOG_PRI(c
->syslog_priority
), &lvl_str
);
3392 "%sSyslogFacility: %s\n"
3393 "%sSyslogLevel: %s\n",
3394 prefix
, strna(fac_str
),
3395 prefix
, strna(lvl_str
));
3399 fprintf(f
, "%sSecure Bits:%s%s%s%s%s%s\n",
3401 (c
->secure_bits
& 1<<SECURE_KEEP_CAPS
) ? " keep-caps" : "",
3402 (c
->secure_bits
& 1<<SECURE_KEEP_CAPS_LOCKED
) ? " keep-caps-locked" : "",
3403 (c
->secure_bits
& 1<<SECURE_NO_SETUID_FIXUP
) ? " no-setuid-fixup" : "",
3404 (c
->secure_bits
& 1<<SECURE_NO_SETUID_FIXUP_LOCKED
) ? " no-setuid-fixup-locked" : "",
3405 (c
->secure_bits
& 1<<SECURE_NOROOT
) ? " noroot" : "",
3406 (c
->secure_bits
& 1<<SECURE_NOROOT_LOCKED
) ? "noroot-locked" : "");
3408 if (c
->capability_bounding_set
!= CAP_ALL
) {
3410 fprintf(f
, "%sCapabilityBoundingSet:", prefix
);
3412 for (l
= 0; l
<= cap_last_cap(); l
++)
3413 if (c
->capability_bounding_set
& (UINT64_C(1) << l
))
3414 fprintf(f
, " %s", strna(capability_to_name(l
)));
3419 if (c
->capability_ambient_set
!= 0) {
3421 fprintf(f
, "%sAmbientCapabilities:", prefix
);
3423 for (l
= 0; l
<= cap_last_cap(); l
++)
3424 if (c
->capability_ambient_set
& (UINT64_C(1) << l
))
3425 fprintf(f
, " %s", strna(capability_to_name(l
)));
3431 fprintf(f
, "%sUser: %s\n", prefix
, c
->user
);
3433 fprintf(f
, "%sGroup: %s\n", prefix
, c
->group
);
3435 fprintf(f
, "%sDynamicUser: %s\n", prefix
, yes_no(c
->dynamic_user
));
3437 if (strv_length(c
->supplementary_groups
) > 0) {
3438 fprintf(f
, "%sSupplementaryGroups:", prefix
);
3439 strv_fprintf(f
, c
->supplementary_groups
);
3444 fprintf(f
, "%sPAMName: %s\n", prefix
, c
->pam_name
);
3446 if (strv_length(c
->read_write_paths
) > 0) {
3447 fprintf(f
, "%sReadWritePaths:", prefix
);
3448 strv_fprintf(f
, c
->read_write_paths
);
3452 if (strv_length(c
->read_only_paths
) > 0) {
3453 fprintf(f
, "%sReadOnlyPaths:", prefix
);
3454 strv_fprintf(f
, c
->read_only_paths
);
3458 if (strv_length(c
->inaccessible_paths
) > 0) {
3459 fprintf(f
, "%sInaccessiblePaths:", prefix
);
3460 strv_fprintf(f
, c
->inaccessible_paths
);
3466 "%sUtmpIdentifier: %s\n",
3467 prefix
, c
->utmp_id
);
3469 if (c
->selinux_context
)
3471 "%sSELinuxContext: %s%s\n",
3472 prefix
, c
->selinux_context_ignore
? "-" : "", c
->selinux_context
);
3474 if (c
->personality
!= PERSONALITY_INVALID
)
3476 "%sPersonality: %s\n",
3477 prefix
, strna(personality_to_string(c
->personality
)));
3479 if (c
->syscall_filter
) {
3487 "%sSystemCallFilter: ",
3490 if (!c
->syscall_whitelist
)
3494 SET_FOREACH(id
, c
->syscall_filter
, j
) {
3495 _cleanup_free_
char *name
= NULL
;
3502 name
= seccomp_syscall_resolve_num_arch(SCMP_ARCH_NATIVE
, PTR_TO_INT(id
) - 1);
3503 fputs(strna(name
), f
);
3510 if (c
->syscall_archs
) {
3517 "%sSystemCallArchitectures:",
3521 SET_FOREACH(id
, c
->syscall_archs
, j
)
3522 fprintf(f
, " %s", strna(seccomp_arch_to_string(PTR_TO_UINT32(id
) - 1)));
3527 if (c
->syscall_errno
> 0)
3529 "%sSystemCallErrorNumber: %s\n",
3530 prefix
, strna(errno_to_name(c
->syscall_errno
)));
3532 if (c
->apparmor_profile
)
3534 "%sAppArmorProfile: %s%s\n",
3535 prefix
, c
->apparmor_profile_ignore
? "-" : "", c
->apparmor_profile
);
3538 bool exec_context_maintains_privileges(ExecContext
*c
) {
3541 /* Returns true if the process forked off would run under
3542 * an unchanged UID or as root. */
3547 if (streq(c
->user
, "root") || streq(c
->user
, "0"))
3553 void exec_status_start(ExecStatus
*s
, pid_t pid
) {
3558 dual_timestamp_get(&s
->start_timestamp
);
3561 void exec_status_exit(ExecStatus
*s
, ExecContext
*context
, pid_t pid
, int code
, int status
) {
3564 if (s
->pid
&& s
->pid
!= pid
)
3568 dual_timestamp_get(&s
->exit_timestamp
);
3574 if (context
->utmp_id
)
3575 utmp_put_dead_process(context
->utmp_id
, pid
, code
, status
);
3577 exec_context_tty_reset(context
, NULL
);
3581 void exec_status_dump(ExecStatus
*s
, FILE *f
, const char *prefix
) {
3582 char buf
[FORMAT_TIMESTAMP_MAX
];
3590 prefix
= strempty(prefix
);
3593 "%sPID: "PID_FMT
"\n",
3596 if (dual_timestamp_is_set(&s
->start_timestamp
))
3598 "%sStart Timestamp: %s\n",
3599 prefix
, format_timestamp(buf
, sizeof(buf
), s
->start_timestamp
.realtime
));
3601 if (dual_timestamp_is_set(&s
->exit_timestamp
))
3603 "%sExit Timestamp: %s\n"
3605 "%sExit Status: %i\n",
3606 prefix
, format_timestamp(buf
, sizeof(buf
), s
->exit_timestamp
.realtime
),
3607 prefix
, sigchld_code_to_string(s
->code
),
3611 char *exec_command_line(char **argv
) {
3619 STRV_FOREACH(a
, argv
)
3627 STRV_FOREACH(a
, argv
) {
3634 if (strpbrk(*a
, WHITESPACE
)) {
3645 /* FIXME: this doesn't really handle arguments that have
3646 * spaces and ticks in them */
3651 void exec_command_dump(ExecCommand
*c
, FILE *f
, const char *prefix
) {
3652 _cleanup_free_
char *cmd
= NULL
;
3653 const char *prefix2
;
3658 prefix
= strempty(prefix
);
3659 prefix2
= strjoina(prefix
, "\t");
3661 cmd
= exec_command_line(c
->argv
);
3663 "%sCommand Line: %s\n",
3664 prefix
, cmd
? cmd
: strerror(ENOMEM
));
3666 exec_status_dump(&c
->exec_status
, f
, prefix2
);
3669 void exec_command_dump_list(ExecCommand
*c
, FILE *f
, const char *prefix
) {
3672 prefix
= strempty(prefix
);
3674 LIST_FOREACH(command
, c
, c
)
3675 exec_command_dump(c
, f
, prefix
);
3678 void exec_command_append_list(ExecCommand
**l
, ExecCommand
*e
) {
3685 /* It's kind of important, that we keep the order here */
3686 LIST_FIND_TAIL(command
, *l
, end
);
3687 LIST_INSERT_AFTER(command
, *l
, end
, e
);
3692 int exec_command_set(ExecCommand
*c
, const char *path
, ...) {
3700 l
= strv_new_ap(path
, ap
);
3721 int exec_command_append(ExecCommand
*c
, const char *path
, ...) {
3722 _cleanup_strv_free_
char **l
= NULL
;
3730 l
= strv_new_ap(path
, ap
);
3736 r
= strv_extend_strv(&c
->argv
, l
, false);
3744 static int exec_runtime_allocate(ExecRuntime
**rt
) {
3749 *rt
= new0(ExecRuntime
, 1);
3754 (*rt
)->netns_storage_socket
[0] = (*rt
)->netns_storage_socket
[1] = -1;
3759 int exec_runtime_make(ExecRuntime
**rt
, ExecContext
*c
, const char *id
) {
3769 if (!c
->private_network
&& !c
->private_tmp
)
3772 r
= exec_runtime_allocate(rt
);
3776 if (c
->private_network
&& (*rt
)->netns_storage_socket
[0] < 0) {
3777 if (socketpair(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
, 0, (*rt
)->netns_storage_socket
) < 0)
3781 if (c
->private_tmp
&& !(*rt
)->tmp_dir
) {
3782 r
= setup_tmp_dirs(id
, &(*rt
)->tmp_dir
, &(*rt
)->var_tmp_dir
);
3790 ExecRuntime
*exec_runtime_ref(ExecRuntime
*r
) {
3792 assert(r
->n_ref
> 0);
3798 ExecRuntime
*exec_runtime_unref(ExecRuntime
*r
) {
3803 assert(r
->n_ref
> 0);
3810 free(r
->var_tmp_dir
);
3811 safe_close_pair(r
->netns_storage_socket
);
3815 int exec_runtime_serialize(Unit
*u
, ExecRuntime
*rt
, FILE *f
, FDSet
*fds
) {
3824 unit_serialize_item(u
, f
, "tmp-dir", rt
->tmp_dir
);
3826 if (rt
->var_tmp_dir
)
3827 unit_serialize_item(u
, f
, "var-tmp-dir", rt
->var_tmp_dir
);
3829 if (rt
->netns_storage_socket
[0] >= 0) {
3832 copy
= fdset_put_dup(fds
, rt
->netns_storage_socket
[0]);
3836 unit_serialize_item_format(u
, f
, "netns-socket-0", "%i", copy
);
3839 if (rt
->netns_storage_socket
[1] >= 0) {
3842 copy
= fdset_put_dup(fds
, rt
->netns_storage_socket
[1]);
3846 unit_serialize_item_format(u
, f
, "netns-socket-1", "%i", copy
);
3852 int exec_runtime_deserialize_item(Unit
*u
, ExecRuntime
**rt
, const char *key
, const char *value
, FDSet
*fds
) {
3859 if (streq(key
, "tmp-dir")) {
3862 r
= exec_runtime_allocate(rt
);
3866 copy
= strdup(value
);
3870 free((*rt
)->tmp_dir
);
3871 (*rt
)->tmp_dir
= copy
;
3873 } else if (streq(key
, "var-tmp-dir")) {
3876 r
= exec_runtime_allocate(rt
);
3880 copy
= strdup(value
);
3884 free((*rt
)->var_tmp_dir
);
3885 (*rt
)->var_tmp_dir
= copy
;
3887 } else if (streq(key
, "netns-socket-0")) {
3890 r
= exec_runtime_allocate(rt
);
3894 if (safe_atoi(value
, &fd
) < 0 || !fdset_contains(fds
, fd
))
3895 log_unit_debug(u
, "Failed to parse netns socket value: %s", value
);
3897 safe_close((*rt
)->netns_storage_socket
[0]);
3898 (*rt
)->netns_storage_socket
[0] = fdset_remove(fds
, fd
);
3900 } else if (streq(key
, "netns-socket-1")) {
3903 r
= exec_runtime_allocate(rt
);
3907 if (safe_atoi(value
, &fd
) < 0 || !fdset_contains(fds
, fd
))
3908 log_unit_debug(u
, "Failed to parse netns socket value: %s", value
);
3910 safe_close((*rt
)->netns_storage_socket
[1]);
3911 (*rt
)->netns_storage_socket
[1] = fdset_remove(fds
, fd
);
3919 static void *remove_tmpdir_thread(void *p
) {
3920 _cleanup_free_
char *path
= p
;
3922 (void) rm_rf(path
, REMOVE_ROOT
|REMOVE_PHYSICAL
);
3926 void exec_runtime_destroy(ExecRuntime
*rt
) {
3932 /* If there are multiple users of this, let's leave the stuff around */
3937 log_debug("Spawning thread to nuke %s", rt
->tmp_dir
);
3939 r
= asynchronous_job(remove_tmpdir_thread
, rt
->tmp_dir
);
3941 log_warning_errno(r
, "Failed to nuke %s: %m", rt
->tmp_dir
);
3948 if (rt
->var_tmp_dir
) {
3949 log_debug("Spawning thread to nuke %s", rt
->var_tmp_dir
);
3951 r
= asynchronous_job(remove_tmpdir_thread
, rt
->var_tmp_dir
);
3953 log_warning_errno(r
, "Failed to nuke %s: %m", rt
->var_tmp_dir
);
3954 free(rt
->var_tmp_dir
);
3957 rt
->var_tmp_dir
= NULL
;
3960 safe_close_pair(rt
->netns_storage_socket
);
3963 static const char* const exec_input_table
[_EXEC_INPUT_MAX
] = {
3964 [EXEC_INPUT_NULL
] = "null",
3965 [EXEC_INPUT_TTY
] = "tty",
3966 [EXEC_INPUT_TTY_FORCE
] = "tty-force",
3967 [EXEC_INPUT_TTY_FAIL
] = "tty-fail",
3968 [EXEC_INPUT_SOCKET
] = "socket",
3969 [EXEC_INPUT_NAMED_FD
] = "fd",
3972 DEFINE_STRING_TABLE_LOOKUP(exec_input
, ExecInput
);
3974 static const char* const exec_output_table
[_EXEC_OUTPUT_MAX
] = {
3975 [EXEC_OUTPUT_INHERIT
] = "inherit",
3976 [EXEC_OUTPUT_NULL
] = "null",
3977 [EXEC_OUTPUT_TTY
] = "tty",
3978 [EXEC_OUTPUT_SYSLOG
] = "syslog",
3979 [EXEC_OUTPUT_SYSLOG_AND_CONSOLE
] = "syslog+console",
3980 [EXEC_OUTPUT_KMSG
] = "kmsg",
3981 [EXEC_OUTPUT_KMSG_AND_CONSOLE
] = "kmsg+console",
3982 [EXEC_OUTPUT_JOURNAL
] = "journal",
3983 [EXEC_OUTPUT_JOURNAL_AND_CONSOLE
] = "journal+console",
3984 [EXEC_OUTPUT_SOCKET
] = "socket",
3985 [EXEC_OUTPUT_NAMED_FD
] = "fd",
3988 DEFINE_STRING_TABLE_LOOKUP(exec_output
, ExecOutput
);
3990 static const char* const exec_utmp_mode_table
[_EXEC_UTMP_MODE_MAX
] = {
3991 [EXEC_UTMP_INIT
] = "init",
3992 [EXEC_UTMP_LOGIN
] = "login",
3993 [EXEC_UTMP_USER
] = "user",
3996 DEFINE_STRING_TABLE_LOOKUP(exec_utmp_mode
, ExecUtmpMode
);