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 "format-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(const char *vc
, 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(vc
, false, false, false, DEFAULT_CONFIRM_USEC
);
646 r
= chown_terminal(fd
, getuid());
650 r
= reset_terminal_fd(fd
, true);
654 if (dup2(fd
, STDIN_FILENO
) < 0)
657 if (dup2(fd
, STDOUT_FILENO
) < 0)
664 *_saved_stdin
= saved_stdin
;
665 *_saved_stdout
= saved_stdout
;
667 saved_stdin
= saved_stdout
= -1;
672 static void write_confirm_error_fd(int err
, int fd
) {
675 if (err
== -ETIMEDOUT
)
676 dprintf(fd
, "Confirmation question timed out, assuming positive response.\n");
679 dprintf(fd
, "Couldn't ask confirmation: %m, assuming positive response.\n");
683 static void write_confirm_error(int err
, const char *vc
) {
684 _cleanup_close_
int fd
= -1;
688 fd
= open_terminal(vc
, O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
692 write_confirm_error_fd(err
, fd
);
695 static int restore_confirm_stdio(int *saved_stdin
, int *saved_stdout
) {
699 assert(saved_stdout
);
703 if (*saved_stdin
>= 0)
704 if (dup2(*saved_stdin
, STDIN_FILENO
) < 0)
707 if (*saved_stdout
>= 0)
708 if (dup2(*saved_stdout
, STDOUT_FILENO
) < 0)
711 *saved_stdin
= safe_close(*saved_stdin
);
712 *saved_stdout
= safe_close(*saved_stdout
);
718 CONFIRM_PRETEND_FAILURE
= -1,
719 CONFIRM_PRETEND_SUCCESS
= 0,
723 static int ask_for_confirmation(const char *vc
, const char *cmdline
) {
724 int saved_stdout
= -1, saved_stdin
= -1, r
;
725 _cleanup_free_
char *e
= NULL
;
728 /* For any internal errors, assume a positive response. */
729 r
= setup_confirm_stdio(vc
, &saved_stdin
, &saved_stdout
);
731 write_confirm_error(r
, vc
);
732 return CONFIRM_EXECUTE
;
735 e
= ellipsize(cmdline
, 60, 100);
743 r
= ask_char(&c
, "yfsh", "Execute %s? [y, f, s – h for help] ", e
);
745 write_confirm_error_fd(r
, STDOUT_FILENO
);
752 printf("Failing execution.\n");
753 r
= CONFIRM_PRETEND_FAILURE
;
756 printf(" f - fail, don't execute the command and pretend it failed\n"
758 " s - skip, don't execute the command and pretend it succeeded\n"
759 " y - yes, execute the command\n");
762 printf("Skipping execution.\n");
763 r
= CONFIRM_PRETEND_SUCCESS
;
769 assert_not_reached("Unhandled choice");
775 restore_confirm_stdio(&saved_stdin
, &saved_stdout
);
779 static int get_fixed_user(const ExecContext
*c
, const char **user
,
780 uid_t
*uid
, gid_t
*gid
,
781 const char **home
, const char **shell
) {
790 /* Note that we don't set $HOME or $SHELL if they are not particularly enlightening anyway
791 * (i.e. are "/" or "/bin/nologin"). */
794 r
= get_user_creds_clean(&name
, uid
, gid
, home
, shell
);
802 static int get_fixed_group(const ExecContext
*c
, const char **group
, gid_t
*gid
) {
812 r
= get_group_creds(&name
, gid
);
820 static int get_supplementary_groups(const ExecContext
*c
, const char *user
,
821 const char *group
, gid_t gid
,
822 gid_t
**supplementary_gids
, int *ngids
) {
826 bool keep_groups
= false;
827 gid_t
*groups
= NULL
;
828 _cleanup_free_ gid_t
*l_gids
= NULL
;
833 * If user is given, then lookup GID and supplementary groups list.
834 * We avoid NSS lookups for gid=0. Also we have to initialize groups
835 * here and as early as possible so we keep the list of supplementary
836 * groups of the caller.
838 if (user
&& gid_is_valid(gid
) && gid
!= 0) {
839 /* First step, initialize groups from /etc/groups */
840 if (initgroups(user
, gid
) < 0)
846 if (!c
->supplementary_groups
)
850 * If SupplementaryGroups= was passed then NGROUPS_MAX has to
851 * be positive, otherwise fail.
854 ngroups_max
= (int) sysconf(_SC_NGROUPS_MAX
);
855 if (ngroups_max
<= 0) {
859 return -EOPNOTSUPP
; /* For all other values */
862 l_gids
= new(gid_t
, ngroups_max
);
868 * Lookup the list of groups that the user belongs to, we
869 * avoid NSS lookups here too for gid=0.
872 if (getgrouplist(user
, gid
, l_gids
, &k
) < 0)
877 STRV_FOREACH(i
, c
->supplementary_groups
) {
880 if (k
>= ngroups_max
)
884 r
= get_group_creds(&g
, l_gids
+k
);
892 * Sets ngids to zero to drop all supplementary groups, happens
893 * when we are under root and SupplementaryGroups= is empty.
900 /* Otherwise get the final list of supplementary groups */
901 groups
= memdup(l_gids
, sizeof(gid_t
) * k
);
905 *supplementary_gids
= groups
;
913 static int enforce_groups(const ExecContext
*context
, gid_t gid
,
914 gid_t
*supplementary_gids
, int ngids
) {
919 /* Handle SupplementaryGroups= even if it is empty */
920 if (context
->supplementary_groups
) {
921 r
= maybe_setgroups(ngids
, supplementary_gids
);
926 if (gid_is_valid(gid
)) {
927 /* Then set our gids */
928 if (setresgid(gid
, gid
, gid
) < 0)
935 static int enforce_user(const ExecContext
*context
, uid_t uid
) {
938 if (!uid_is_valid(uid
))
941 /* Sets (but doesn't look up) the uid and make sure we keep the
942 * capabilities while doing so. */
944 if (context
->capability_ambient_set
!= 0) {
946 /* First step: If we need to keep capabilities but
947 * drop privileges we need to make sure we keep our
948 * caps, while we drop privileges. */
950 int sb
= context
->secure_bits
| 1<<SECURE_KEEP_CAPS
;
952 if (prctl(PR_GET_SECUREBITS
) != sb
)
953 if (prctl(PR_SET_SECUREBITS
, sb
) < 0)
958 /* Second step: actually set the uids */
959 if (setresuid(uid
, uid
, uid
) < 0)
962 /* At this point we should have all necessary capabilities but
963 are otherwise a normal user. However, the caps might got
964 corrupted due to the setresuid() so we need clean them up
965 later. This is done outside of this call. */
972 static int null_conv(
974 const struct pam_message
**msg
,
975 struct pam_response
**resp
,
978 /* We don't support conversations */
985 static int setup_pam(
992 int fds
[], unsigned n_fds
) {
996 static const struct pam_conv conv
= {
1001 _cleanup_(barrier_destroy
) Barrier barrier
= BARRIER_NULL
;
1002 pam_handle_t
*handle
= NULL
;
1004 int pam_code
= PAM_SUCCESS
, r
;
1005 char **nv
, **e
= NULL
;
1006 bool close_session
= false;
1007 pid_t pam_pid
= 0, parent_pid
;
1014 /* We set up PAM in the parent process, then fork. The child
1015 * will then stay around until killed via PR_GET_PDEATHSIG or
1016 * systemd via the cgroup logic. It will then remove the PAM
1017 * session again. The parent process will exec() the actual
1018 * daemon. We do things this way to ensure that the main PID
1019 * of the daemon is the one we initially fork()ed. */
1021 r
= barrier_create(&barrier
);
1025 if (log_get_max_level() < LOG_DEBUG
)
1026 flags
|= PAM_SILENT
;
1028 pam_code
= pam_start(name
, user
, &conv
, &handle
);
1029 if (pam_code
!= PAM_SUCCESS
) {
1035 pam_code
= pam_set_item(handle
, PAM_TTY
, tty
);
1036 if (pam_code
!= PAM_SUCCESS
)
1040 STRV_FOREACH(nv
, *env
) {
1041 pam_code
= pam_putenv(handle
, *nv
);
1042 if (pam_code
!= PAM_SUCCESS
)
1046 pam_code
= pam_acct_mgmt(handle
, flags
);
1047 if (pam_code
!= PAM_SUCCESS
)
1050 pam_code
= pam_open_session(handle
, flags
);
1051 if (pam_code
!= PAM_SUCCESS
)
1054 close_session
= true;
1056 e
= pam_getenvlist(handle
);
1058 pam_code
= PAM_BUF_ERR
;
1062 /* Block SIGTERM, so that we know that it won't get lost in
1065 assert_se(sigprocmask_many(SIG_BLOCK
, &old_ss
, SIGTERM
, -1) >= 0);
1067 parent_pid
= getpid();
1076 int sig
, ret
= EXIT_PAM
;
1078 /* The child's job is to reset the PAM session on
1080 barrier_set_role(&barrier
, BARRIER_CHILD
);
1082 /* This string must fit in 10 chars (i.e. the length
1083 * of "/sbin/init"), to look pretty in /bin/ps */
1084 rename_process("(sd-pam)");
1086 /* Make sure we don't keep open the passed fds in this
1087 child. We assume that otherwise only those fds are
1088 open here that have been opened by PAM. */
1089 close_many(fds
, n_fds
);
1091 /* Drop privileges - we don't need any to pam_close_session
1092 * and this will make PR_SET_PDEATHSIG work in most cases.
1093 * If this fails, ignore the error - but expect sd-pam threads
1094 * to fail to exit normally */
1096 r
= maybe_setgroups(0, NULL
);
1098 log_warning_errno(r
, "Failed to setgroups() in sd-pam: %m");
1099 if (setresgid(gid
, gid
, gid
) < 0)
1100 log_warning_errno(errno
, "Failed to setresgid() in sd-pam: %m");
1101 if (setresuid(uid
, uid
, uid
) < 0)
1102 log_warning_errno(errno
, "Failed to setresuid() in sd-pam: %m");
1104 (void) ignore_signals(SIGPIPE
, -1);
1106 /* Wait until our parent died. This will only work if
1107 * the above setresuid() succeeds, otherwise the kernel
1108 * will not allow unprivileged parents kill their privileged
1109 * children this way. We rely on the control groups kill logic
1110 * to do the rest for us. */
1111 if (prctl(PR_SET_PDEATHSIG
, SIGTERM
) < 0)
1114 /* Tell the parent that our setup is done. This is especially
1115 * important regarding dropping privileges. Otherwise, unit
1116 * setup might race against our setresuid(2) call. */
1117 barrier_place(&barrier
);
1119 /* Check if our parent process might already have
1121 if (getppid() == parent_pid
) {
1124 assert_se(sigemptyset(&ss
) >= 0);
1125 assert_se(sigaddset(&ss
, SIGTERM
) >= 0);
1128 if (sigwait(&ss
, &sig
) < 0) {
1135 assert(sig
== SIGTERM
);
1140 /* If our parent died we'll end the session */
1141 if (getppid() != parent_pid
) {
1142 pam_code
= pam_close_session(handle
, flags
);
1143 if (pam_code
!= PAM_SUCCESS
)
1150 pam_end(handle
, pam_code
| flags
);
1154 barrier_set_role(&barrier
, BARRIER_PARENT
);
1156 /* If the child was forked off successfully it will do all the
1157 * cleanups, so forget about the handle here. */
1160 /* Unblock SIGTERM again in the parent */
1161 assert_se(sigprocmask(SIG_SETMASK
, &old_ss
, NULL
) >= 0);
1163 /* We close the log explicitly here, since the PAM modules
1164 * might have opened it, but we don't want this fd around. */
1167 /* Synchronously wait for the child to initialize. We don't care for
1168 * errors as we cannot recover. However, warn loudly if it happens. */
1169 if (!barrier_place_and_sync(&barrier
))
1170 log_error("PAM initialization failed");
1178 if (pam_code
!= PAM_SUCCESS
) {
1179 log_error("PAM failed: %s", pam_strerror(handle
, pam_code
));
1180 r
= -EPERM
; /* PAM errors do not map to errno */
1182 log_error_errno(r
, "PAM failed: %m");
1186 pam_code
= pam_close_session(handle
, flags
);
1188 pam_end(handle
, pam_code
| flags
);
1200 static void rename_process_from_path(const char *path
) {
1201 char process_name
[11];
1205 /* This resulting string must fit in 10 chars (i.e. the length
1206 * of "/sbin/init") to look pretty in /bin/ps */
1210 rename_process("(...)");
1216 /* The end of the process name is usually more
1217 * interesting, since the first bit might just be
1223 process_name
[0] = '(';
1224 memcpy(process_name
+1, p
, l
);
1225 process_name
[1+l
] = ')';
1226 process_name
[1+l
+1] = 0;
1228 rename_process(process_name
);
1233 static bool skip_seccomp_unavailable(const Unit
* u
, const char* msg
) {
1235 if (is_seccomp_available())
1239 log_unit_debug(u
, "SECCOMP features not detected in the kernel, skipping %s", msg
);
1244 static int apply_seccomp(const Unit
* u
, const ExecContext
*c
) {
1245 uint32_t negative_action
, action
;
1246 scmp_filter_ctx seccomp
;
1253 if (skip_seccomp_unavailable(u
, "syscall filtering"))
1256 negative_action
= c
->syscall_errno
== 0 ? SCMP_ACT_KILL
: SCMP_ACT_ERRNO(c
->syscall_errno
);
1258 seccomp
= seccomp_init(c
->syscall_whitelist
? negative_action
: SCMP_ACT_ALLOW
);
1262 if (c
->syscall_archs
) {
1264 SET_FOREACH(id
, c
->syscall_archs
, i
) {
1265 r
= seccomp_arch_add(seccomp
, PTR_TO_UINT32(id
) - 1);
1273 r
= seccomp_add_secondary_archs(seccomp
);
1278 action
= c
->syscall_whitelist
? SCMP_ACT_ALLOW
: negative_action
;
1279 SET_FOREACH(id
, c
->syscall_filter
, i
) {
1280 r
= seccomp_rule_add(seccomp
, action
, PTR_TO_INT(id
) - 1, 0);
1285 r
= seccomp_attr_set(seccomp
, SCMP_FLTATR_CTL_NNP
, 0);
1289 r
= seccomp_load(seccomp
);
1292 seccomp_release(seccomp
);
1296 static int apply_address_families(const Unit
* u
, const ExecContext
*c
) {
1297 scmp_filter_ctx seccomp
;
1303 if (skip_seccomp_unavailable(u
, "RestrictAddressFamilies="))
1306 r
= seccomp_init_conservative(&seccomp
, SCMP_ACT_ALLOW
);
1310 if (c
->address_families_whitelist
) {
1311 int af
, first
= 0, last
= 0;
1314 /* If this is a whitelist, we first block the address
1315 * families that are out of range and then everything
1316 * that is not in the set. First, we find the lowest
1317 * and highest address family in the set. */
1319 SET_FOREACH(afp
, c
->address_families
, i
) {
1320 af
= PTR_TO_INT(afp
);
1322 if (af
<= 0 || af
>= af_max())
1325 if (first
== 0 || af
< first
)
1328 if (last
== 0 || af
> last
)
1332 assert((first
== 0) == (last
== 0));
1336 /* No entries in the valid range, block everything */
1337 r
= seccomp_rule_add(
1339 SCMP_ACT_ERRNO(EPROTONOSUPPORT
),
1347 /* Block everything below the first entry */
1348 r
= seccomp_rule_add(
1350 SCMP_ACT_ERRNO(EPROTONOSUPPORT
),
1353 SCMP_A0(SCMP_CMP_LT
, first
));
1357 /* Block everything above the last entry */
1358 r
= seccomp_rule_add(
1360 SCMP_ACT_ERRNO(EPROTONOSUPPORT
),
1363 SCMP_A0(SCMP_CMP_GT
, last
));
1367 /* Block everything between the first and last
1369 for (af
= 1; af
< af_max(); af
++) {
1371 if (set_contains(c
->address_families
, INT_TO_PTR(af
)))
1374 r
= seccomp_rule_add(
1376 SCMP_ACT_ERRNO(EPROTONOSUPPORT
),
1379 SCMP_A0(SCMP_CMP_EQ
, af
));
1388 /* If this is a blacklist, then generate one rule for
1389 * each address family that are then combined in OR
1392 SET_FOREACH(af
, c
->address_families
, i
) {
1394 r
= seccomp_rule_add(
1396 SCMP_ACT_ERRNO(EPROTONOSUPPORT
),
1399 SCMP_A0(SCMP_CMP_EQ
, PTR_TO_INT(af
)));
1405 r
= seccomp_load(seccomp
);
1408 seccomp_release(seccomp
);
1412 static int apply_memory_deny_write_execute(const Unit
* u
, const ExecContext
*c
) {
1413 scmp_filter_ctx seccomp
;
1418 if (skip_seccomp_unavailable(u
, "MemoryDenyWriteExecute="))
1421 r
= seccomp_init_conservative(&seccomp
, SCMP_ACT_ALLOW
);
1425 r
= seccomp_rule_add(
1427 SCMP_ACT_ERRNO(EPERM
),
1430 SCMP_A2(SCMP_CMP_MASKED_EQ
, PROT_EXEC
|PROT_WRITE
, PROT_EXEC
|PROT_WRITE
));
1434 r
= seccomp_rule_add(
1436 SCMP_ACT_ERRNO(EPERM
),
1439 SCMP_A2(SCMP_CMP_MASKED_EQ
, PROT_EXEC
, PROT_EXEC
));
1443 r
= seccomp_rule_add(
1445 SCMP_ACT_ERRNO(EPERM
),
1448 SCMP_A2(SCMP_CMP_MASKED_EQ
, SHM_EXEC
, SHM_EXEC
));
1452 r
= seccomp_load(seccomp
);
1455 seccomp_release(seccomp
);
1459 static int apply_restrict_realtime(const Unit
* u
, const ExecContext
*c
) {
1460 static const int permitted_policies
[] = {
1466 scmp_filter_ctx seccomp
;
1468 int r
, p
, max_policy
= 0;
1472 if (skip_seccomp_unavailable(u
, "RestrictRealtime="))
1475 r
= seccomp_init_conservative(&seccomp
, SCMP_ACT_ALLOW
);
1479 /* Determine the highest policy constant we want to allow */
1480 for (i
= 0; i
< ELEMENTSOF(permitted_policies
); i
++)
1481 if (permitted_policies
[i
] > max_policy
)
1482 max_policy
= permitted_policies
[i
];
1484 /* Go through all policies with lower values than that, and block them -- unless they appear in the
1486 for (p
= 0; p
< max_policy
; p
++) {
1489 /* Check if this is in the whitelist. */
1490 for (i
= 0; i
< ELEMENTSOF(permitted_policies
); i
++)
1491 if (permitted_policies
[i
] == p
) {
1499 /* Deny this policy */
1500 r
= seccomp_rule_add(
1502 SCMP_ACT_ERRNO(EPERM
),
1503 SCMP_SYS(sched_setscheduler
),
1505 SCMP_A1(SCMP_CMP_EQ
, p
));
1510 /* Blacklist all other policies, i.e. the ones with higher values. Note that all comparisons are unsigned here,
1511 * hence no need no check for < 0 values. */
1512 r
= seccomp_rule_add(
1514 SCMP_ACT_ERRNO(EPERM
),
1515 SCMP_SYS(sched_setscheduler
),
1517 SCMP_A1(SCMP_CMP_GT
, max_policy
));
1521 r
= seccomp_load(seccomp
);
1524 seccomp_release(seccomp
);
1528 static int apply_protect_sysctl(const Unit
*u
, const ExecContext
*c
) {
1529 scmp_filter_ctx seccomp
;
1534 /* Turn off the legacy sysctl() system call. Many distributions turn this off while building the kernel, but
1535 * let's protect even those systems where this is left on in the kernel. */
1537 if (skip_seccomp_unavailable(u
, "ProtectKernelTunables="))
1540 r
= seccomp_init_conservative(&seccomp
, SCMP_ACT_ALLOW
);
1544 r
= seccomp_rule_add(
1546 SCMP_ACT_ERRNO(EPERM
),
1552 r
= seccomp_load(seccomp
);
1555 seccomp_release(seccomp
);
1559 static int apply_protect_kernel_modules(const Unit
*u
, const ExecContext
*c
) {
1562 /* Turn off module syscalls on ProtectKernelModules=yes */
1564 if (skip_seccomp_unavailable(u
, "ProtectKernelModules="))
1567 return seccomp_load_filter_set(SCMP_ACT_ALLOW
, syscall_filter_sets
+ SYSCALL_FILTER_SET_MODULE
, SCMP_ACT_ERRNO(EPERM
));
1570 static int apply_private_devices(const Unit
*u
, const ExecContext
*c
) {
1573 /* If PrivateDevices= is set, also turn off iopl and all @raw-io syscalls. */
1575 if (skip_seccomp_unavailable(u
, "PrivateDevices="))
1578 return seccomp_load_filter_set(SCMP_ACT_ALLOW
, syscall_filter_sets
+ SYSCALL_FILTER_SET_RAW_IO
, SCMP_ACT_ERRNO(EPERM
));
1581 static int apply_restrict_namespaces(Unit
*u
, const ExecContext
*c
) {
1584 if (!exec_context_restrict_namespaces_set(c
))
1587 if (skip_seccomp_unavailable(u
, "RestrictNamespaces="))
1590 return seccomp_restrict_namespaces(c
->restrict_namespaces
);
1595 static void do_idle_pipe_dance(int idle_pipe
[4]) {
1598 idle_pipe
[1] = safe_close(idle_pipe
[1]);
1599 idle_pipe
[2] = safe_close(idle_pipe
[2]);
1601 if (idle_pipe
[0] >= 0) {
1604 r
= fd_wait_for_event(idle_pipe
[0], POLLHUP
, IDLE_TIMEOUT_USEC
);
1606 if (idle_pipe
[3] >= 0 && r
== 0 /* timeout */) {
1609 /* Signal systemd that we are bored and want to continue. */
1610 n
= write(idle_pipe
[3], "x", 1);
1612 /* Wait for systemd to react to the signal above. */
1613 fd_wait_for_event(idle_pipe
[0], POLLHUP
, IDLE_TIMEOUT2_USEC
);
1616 idle_pipe
[0] = safe_close(idle_pipe
[0]);
1620 idle_pipe
[3] = safe_close(idle_pipe
[3]);
1623 static int build_environment(
1625 const ExecContext
*c
,
1626 const ExecParameters
*p
,
1629 const char *username
,
1631 dev_t journal_stream_dev
,
1632 ino_t journal_stream_ino
,
1635 _cleanup_strv_free_
char **our_env
= NULL
;
1643 our_env
= new0(char*, 14);
1648 _cleanup_free_
char *joined
= NULL
;
1650 if (asprintf(&x
, "LISTEN_PID="PID_FMT
, getpid()) < 0)
1652 our_env
[n_env
++] = x
;
1654 if (asprintf(&x
, "LISTEN_FDS=%u", n_fds
) < 0)
1656 our_env
[n_env
++] = x
;
1658 joined
= strv_join(p
->fd_names
, ":");
1662 x
= strjoin("LISTEN_FDNAMES=", joined
);
1665 our_env
[n_env
++] = x
;
1668 if ((p
->flags
& EXEC_SET_WATCHDOG
) && p
->watchdog_usec
> 0) {
1669 if (asprintf(&x
, "WATCHDOG_PID="PID_FMT
, getpid()) < 0)
1671 our_env
[n_env
++] = x
;
1673 if (asprintf(&x
, "WATCHDOG_USEC="USEC_FMT
, p
->watchdog_usec
) < 0)
1675 our_env
[n_env
++] = x
;
1678 /* If this is D-Bus, tell the nss-systemd module, since it relies on being able to use D-Bus look up dynamic
1679 * users via PID 1, possibly dead-locking the dbus daemon. This way it will not use D-Bus to resolve names, but
1680 * check the database directly. */
1681 if (unit_has_name(u
, SPECIAL_DBUS_SERVICE
)) {
1682 x
= strdup("SYSTEMD_NSS_BYPASS_BUS=1");
1685 our_env
[n_env
++] = x
;
1689 x
= strappend("HOME=", home
);
1692 our_env
[n_env
++] = x
;
1696 x
= strappend("LOGNAME=", username
);
1699 our_env
[n_env
++] = x
;
1701 x
= strappend("USER=", username
);
1704 our_env
[n_env
++] = x
;
1708 x
= strappend("SHELL=", shell
);
1711 our_env
[n_env
++] = x
;
1714 if (!sd_id128_is_null(u
->invocation_id
)) {
1715 if (asprintf(&x
, "INVOCATION_ID=" SD_ID128_FORMAT_STR
, SD_ID128_FORMAT_VAL(u
->invocation_id
)) < 0)
1718 our_env
[n_env
++] = x
;
1721 if (exec_context_needs_term(c
)) {
1722 const char *tty_path
, *term
= NULL
;
1724 tty_path
= exec_context_tty_path(c
);
1726 /* If we are forked off PID 1 and we are supposed to operate on /dev/console, then let's try to inherit
1727 * the $TERM set for PID 1. This is useful for containers so that the $TERM the container manager
1728 * passes to PID 1 ends up all the way in the console login shown. */
1730 if (path_equal(tty_path
, "/dev/console") && getppid() == 1)
1731 term
= getenv("TERM");
1733 term
= default_term_for_tty(tty_path
);
1735 x
= strappend("TERM=", term
);
1738 our_env
[n_env
++] = x
;
1741 if (journal_stream_dev
!= 0 && journal_stream_ino
!= 0) {
1742 if (asprintf(&x
, "JOURNAL_STREAM=" DEV_FMT
":" INO_FMT
, journal_stream_dev
, journal_stream_ino
) < 0)
1745 our_env
[n_env
++] = x
;
1748 our_env
[n_env
++] = NULL
;
1749 assert(n_env
<= 12);
1757 static int build_pass_environment(const ExecContext
*c
, char ***ret
) {
1758 _cleanup_strv_free_
char **pass_env
= NULL
;
1759 size_t n_env
= 0, n_bufsize
= 0;
1762 STRV_FOREACH(i
, c
->pass_environment
) {
1763 _cleanup_free_
char *x
= NULL
;
1769 x
= strjoin(*i
, "=", v
);
1772 if (!GREEDY_REALLOC(pass_env
, n_bufsize
, n_env
+ 2))
1774 pass_env
[n_env
++] = x
;
1775 pass_env
[n_env
] = NULL
;
1785 static bool exec_needs_mount_namespace(
1786 const ExecContext
*context
,
1787 const ExecParameters
*params
,
1788 ExecRuntime
*runtime
) {
1793 if (!strv_isempty(context
->read_write_paths
) ||
1794 !strv_isempty(context
->read_only_paths
) ||
1795 !strv_isempty(context
->inaccessible_paths
))
1798 if (context
->mount_flags
!= 0)
1801 if (context
->private_tmp
&& runtime
&& (runtime
->tmp_dir
|| runtime
->var_tmp_dir
))
1804 if (context
->private_devices
||
1805 context
->protect_system
!= PROTECT_SYSTEM_NO
||
1806 context
->protect_home
!= PROTECT_HOME_NO
||
1807 context
->protect_kernel_tunables
||
1808 context
->protect_kernel_modules
||
1809 context
->protect_control_groups
)
1815 static int setup_private_users(uid_t uid
, gid_t gid
) {
1816 _cleanup_free_
char *uid_map
= NULL
, *gid_map
= NULL
;
1817 _cleanup_close_pair_
int errno_pipe
[2] = { -1, -1 };
1818 _cleanup_close_
int unshare_ready_fd
= -1;
1819 _cleanup_(sigkill_waitp
) pid_t pid
= 0;
1825 /* Set up a user namespace and map root to root, the selected UID/GID to itself, and everything else to
1826 * nobody. In order to be able to write this mapping we need CAP_SETUID in the original user namespace, which
1827 * we however lack after opening the user namespace. To work around this we fork() a temporary child process,
1828 * which waits for the parent to create the new user namespace while staying in the original namespace. The
1829 * child then writes the UID mapping, under full privileges. The parent waits for the child to finish and
1830 * continues execution normally. */
1832 if (uid
!= 0 && uid_is_valid(uid
))
1834 "0 0 1\n" /* Map root → root */
1835 UID_FMT
" " UID_FMT
" 1\n", /* Map $UID → $UID */
1838 uid_map
= strdup("0 0 1\n"); /* The case where the above is the same */
1842 if (gid
!= 0 && gid_is_valid(gid
))
1844 "0 0 1\n" /* Map root → root */
1845 GID_FMT
" " GID_FMT
" 1\n", /* Map $GID → $GID */
1848 gid_map
= strdup("0 0 1\n"); /* The case where the above is the same */
1852 /* Create a communication channel so that the parent can tell the child when it finished creating the user
1854 unshare_ready_fd
= eventfd(0, EFD_CLOEXEC
);
1855 if (unshare_ready_fd
< 0)
1858 /* Create a communication channel so that the child can tell the parent a proper error code in case it
1860 if (pipe2(errno_pipe
, O_CLOEXEC
) < 0)
1868 _cleanup_close_
int fd
= -1;
1872 /* Child process, running in the original user namespace. Let's update the parent's UID/GID map from
1873 * here, after the parent opened its own user namespace. */
1876 errno_pipe
[0] = safe_close(errno_pipe
[0]);
1878 /* Wait until the parent unshared the user namespace */
1879 if (read(unshare_ready_fd
, &c
, sizeof(c
)) < 0) {
1884 /* Disable the setgroups() system call in the child user namespace, for good. */
1885 a
= procfs_file_alloca(ppid
, "setgroups");
1886 fd
= open(a
, O_WRONLY
|O_CLOEXEC
);
1888 if (errno
!= ENOENT
) {
1893 /* If the file is missing the kernel is too old, let's continue anyway. */
1895 if (write(fd
, "deny\n", 5) < 0) {
1900 fd
= safe_close(fd
);
1903 /* First write the GID map */
1904 a
= procfs_file_alloca(ppid
, "gid_map");
1905 fd
= open(a
, O_WRONLY
|O_CLOEXEC
);
1910 if (write(fd
, gid_map
, strlen(gid_map
)) < 0) {
1914 fd
= safe_close(fd
);
1916 /* The write the UID map */
1917 a
= procfs_file_alloca(ppid
, "uid_map");
1918 fd
= open(a
, O_WRONLY
|O_CLOEXEC
);
1923 if (write(fd
, uid_map
, strlen(uid_map
)) < 0) {
1928 _exit(EXIT_SUCCESS
);
1931 (void) write(errno_pipe
[1], &r
, sizeof(r
));
1932 _exit(EXIT_FAILURE
);
1935 errno_pipe
[1] = safe_close(errno_pipe
[1]);
1937 if (unshare(CLONE_NEWUSER
) < 0)
1940 /* Let the child know that the namespace is ready now */
1941 if (write(unshare_ready_fd
, &c
, sizeof(c
)) < 0)
1944 /* Try to read an error code from the child */
1945 n
= read(errno_pipe
[0], &r
, sizeof(r
));
1948 if (n
== sizeof(r
)) { /* an error code was sent to us */
1953 if (n
!= 0) /* on success we should have read 0 bytes */
1956 r
= wait_for_terminate(pid
, &si
);
1961 /* If something strange happened with the child, let's consider this fatal, too */
1962 if (si
.si_code
!= CLD_EXITED
|| si
.si_status
!= 0)
1968 static int setup_runtime_directory(
1969 const ExecContext
*context
,
1970 const ExecParameters
*params
,
1980 STRV_FOREACH(rt
, context
->runtime_directory
) {
1981 _cleanup_free_
char *p
;
1983 p
= strjoin(params
->runtime_prefix
, "/", *rt
);
1987 r
= mkdir_p_label(p
, context
->runtime_directory_mode
);
1991 r
= chmod_and_chown(p
, context
->runtime_directory_mode
, uid
, gid
);
1999 static int setup_smack(
2000 const ExecContext
*context
,
2001 const ExecCommand
*command
) {
2009 if (!mac_smack_use())
2012 if (context
->smack_process_label
) {
2013 r
= mac_smack_apply_pid(0, context
->smack_process_label
);
2017 #ifdef SMACK_DEFAULT_PROCESS_LABEL
2019 _cleanup_free_
char *exec_label
= NULL
;
2021 r
= mac_smack_read(command
->path
, SMACK_ATTR_EXEC
, &exec_label
);
2022 if (r
< 0 && r
!= -ENODATA
&& r
!= -EOPNOTSUPP
)
2025 r
= mac_smack_apply_pid(0, exec_label
? : SMACK_DEFAULT_PROCESS_LABEL
);
2035 static int compile_read_write_paths(
2036 const ExecContext
*context
,
2037 const ExecParameters
*params
,
2040 _cleanup_strv_free_
char **l
= NULL
;
2043 /* Compile the list of writable paths. This is the combination of the explicitly configured paths, plus all
2044 * runtime directories. */
2046 if (strv_isempty(context
->read_write_paths
) &&
2047 strv_isempty(context
->runtime_directory
)) {
2048 *ret
= NULL
; /* NOP if neither is set */
2052 l
= strv_copy(context
->read_write_paths
);
2056 STRV_FOREACH(rt
, context
->runtime_directory
) {
2059 s
= strjoin(params
->runtime_prefix
, "/", *rt
);
2063 if (strv_consume(&l
, s
) < 0)
2073 static int apply_mount_namespace(Unit
*u
, const ExecContext
*context
,
2074 const ExecParameters
*params
,
2075 ExecRuntime
*runtime
) {
2077 _cleanup_free_
char **rw
= NULL
;
2078 char *tmp
= NULL
, *var
= NULL
;
2079 const char *root_dir
= NULL
;
2080 NameSpaceInfo ns_info
= {
2081 .ignore_protect_paths
= false,
2082 .private_dev
= context
->private_devices
,
2083 .protect_control_groups
= context
->protect_control_groups
,
2084 .protect_kernel_tunables
= context
->protect_kernel_tunables
,
2085 .protect_kernel_modules
= context
->protect_kernel_modules
,
2090 /* The runtime struct only contains the parent of the private /tmp,
2091 * which is non-accessible to world users. Inside of it there's a /tmp
2092 * that is sticky, and that's the one we want to use here. */
2094 if (context
->private_tmp
&& runtime
) {
2095 if (runtime
->tmp_dir
)
2096 tmp
= strjoina(runtime
->tmp_dir
, "/tmp");
2097 if (runtime
->var_tmp_dir
)
2098 var
= strjoina(runtime
->var_tmp_dir
, "/tmp");
2101 r
= compile_read_write_paths(context
, params
, &rw
);
2105 if (params
->flags
& EXEC_APPLY_CHROOT
)
2106 root_dir
= context
->root_directory
;
2109 * If DynamicUser=no and RootDirectory= is set then lets pass a relaxed
2110 * sandbox info, otherwise enforce it, don't ignore protected paths and
2111 * fail if we are enable to apply the sandbox inside the mount namespace.
2113 if (!context
->dynamic_user
&& root_dir
)
2114 ns_info
.ignore_protect_paths
= true;
2116 r
= setup_namespace(root_dir
, &ns_info
, rw
,
2117 context
->read_only_paths
,
2118 context
->inaccessible_paths
,
2121 context
->protect_home
,
2122 context
->protect_system
,
2123 context
->mount_flags
);
2125 /* If we couldn't set up the namespace this is probably due to a
2126 * missing capability. In this case, silently proceeed. */
2127 if (IN_SET(r
, -EPERM
, -EACCES
)) {
2129 log_unit_debug_errno(u
, r
, "Failed to set up namespace, assuming containerized execution, ignoring: %m");
2137 static int apply_working_directory(const ExecContext
*context
,
2138 const ExecParameters
*params
,
2140 const bool needs_mount_ns
) {
2146 if (context
->working_directory_home
)
2148 else if (context
->working_directory
)
2149 wd
= context
->working_directory
;
2153 if (params
->flags
& EXEC_APPLY_CHROOT
) {
2154 if (!needs_mount_ns
&& context
->root_directory
)
2155 if (chroot(context
->root_directory
) < 0)
2160 d
= strjoina(strempty(context
->root_directory
), "/", strempty(wd
));
2162 if (chdir(d
) < 0 && !context
->working_directory_missing_ok
)
2168 static void append_socket_pair(int *array
, unsigned *n
, int pair
[2]) {
2176 array
[(*n
)++] = pair
[0];
2178 array
[(*n
)++] = pair
[1];
2181 static int close_remaining_fds(
2182 const ExecParameters
*params
,
2183 ExecRuntime
*runtime
,
2184 DynamicCreds
*dcreds
,
2187 int *fds
, unsigned n_fds
) {
2189 unsigned n_dont_close
= 0;
2190 int dont_close
[n_fds
+ 12];
2194 if (params
->stdin_fd
>= 0)
2195 dont_close
[n_dont_close
++] = params
->stdin_fd
;
2196 if (params
->stdout_fd
>= 0)
2197 dont_close
[n_dont_close
++] = params
->stdout_fd
;
2198 if (params
->stderr_fd
>= 0)
2199 dont_close
[n_dont_close
++] = params
->stderr_fd
;
2202 dont_close
[n_dont_close
++] = socket_fd
;
2204 memcpy(dont_close
+ n_dont_close
, fds
, sizeof(int) * n_fds
);
2205 n_dont_close
+= n_fds
;
2209 append_socket_pair(dont_close
, &n_dont_close
, runtime
->netns_storage_socket
);
2213 append_socket_pair(dont_close
, &n_dont_close
, dcreds
->user
->storage_socket
);
2215 append_socket_pair(dont_close
, &n_dont_close
, dcreds
->group
->storage_socket
);
2218 if (user_lookup_fd
>= 0)
2219 dont_close
[n_dont_close
++] = user_lookup_fd
;
2221 return close_all_fds(dont_close
, n_dont_close
);
2224 static bool context_has_address_families(const ExecContext
*c
) {
2227 return c
->address_families_whitelist
||
2228 !set_isempty(c
->address_families
);
2231 static bool context_has_syscall_filters(const ExecContext
*c
) {
2234 return c
->syscall_whitelist
||
2235 !set_isempty(c
->syscall_filter
) ||
2236 !set_isempty(c
->syscall_archs
);
2239 static bool context_has_no_new_privileges(const ExecContext
*c
) {
2242 if (c
->no_new_privileges
)
2245 if (have_effective_cap(CAP_SYS_ADMIN
)) /* if we are privileged, we don't need NNP */
2248 return context_has_address_families(c
) || /* we need NNP if we have any form of seccomp and are unprivileged */
2249 c
->memory_deny_write_execute
||
2250 c
->restrict_realtime
||
2251 exec_context_restrict_namespaces_set(c
) ||
2252 c
->protect_kernel_tunables
||
2253 c
->protect_kernel_modules
||
2254 c
->private_devices
||
2255 context_has_syscall_filters(c
);
2258 static int send_user_lookup(
2266 /* Send the resolved UID/GID to PID 1 after we learnt it. We send a single datagram, containing the UID/GID
2267 * data as well as the unit name. Note that we suppress sending this if no user/group to resolve was
2270 if (user_lookup_fd
< 0)
2273 if (!uid_is_valid(uid
) && !gid_is_valid(gid
))
2276 if (writev(user_lookup_fd
,
2278 { .iov_base
= &uid
, .iov_len
= sizeof(uid
) },
2279 { .iov_base
= &gid
, .iov_len
= sizeof(gid
) },
2280 { .iov_base
= unit
->id
, .iov_len
= strlen(unit
->id
) }}, 3) < 0)
2286 static int exec_child(
2288 ExecCommand
*command
,
2289 const ExecContext
*context
,
2290 const ExecParameters
*params
,
2291 ExecRuntime
*runtime
,
2292 DynamicCreds
*dcreds
,
2296 int *fds
, unsigned n_fds
,
2301 _cleanup_strv_free_
char **our_env
= NULL
, **pass_env
= NULL
, **accum_env
= NULL
, **final_argv
= NULL
;
2302 _cleanup_free_
char *mac_selinux_context_net
= NULL
;
2303 _cleanup_free_ gid_t
*supplementary_gids
= NULL
;
2304 const char *username
= NULL
, *groupname
= NULL
;
2305 const char *home
= NULL
, *shell
= NULL
;
2306 dev_t journal_stream_dev
= 0;
2307 ino_t journal_stream_ino
= 0;
2308 bool needs_mount_namespace
;
2309 uid_t uid
= UID_INVALID
;
2310 gid_t gid
= GID_INVALID
;
2311 int i
, r
, ngids
= 0;
2317 assert(exit_status
);
2319 rename_process_from_path(command
->path
);
2321 /* We reset exactly these signals, since they are the
2322 * only ones we set to SIG_IGN in the main daemon. All
2323 * others we leave untouched because we set them to
2324 * SIG_DFL or a valid handler initially, both of which
2325 * will be demoted to SIG_DFL. */
2326 (void) default_signals(SIGNALS_CRASH_HANDLER
,
2327 SIGNALS_IGNORE
, -1);
2329 if (context
->ignore_sigpipe
)
2330 (void) ignore_signals(SIGPIPE
, -1);
2332 r
= reset_signal_mask();
2334 *exit_status
= EXIT_SIGNAL_MASK
;
2338 if (params
->idle_pipe
)
2339 do_idle_pipe_dance(params
->idle_pipe
);
2341 /* Close sockets very early to make sure we don't
2342 * block init reexecution because it cannot bind its
2347 r
= close_remaining_fds(params
, runtime
, dcreds
, user_lookup_fd
, socket_fd
, fds
, n_fds
);
2349 *exit_status
= EXIT_FDS
;
2353 if (!context
->same_pgrp
)
2355 *exit_status
= EXIT_SETSID
;
2359 exec_context_tty_reset(context
, params
);
2361 if (params
->confirm_spawn
) {
2362 const char *vc
= params
->confirm_spawn
;
2363 _cleanup_free_
char *cmdline
= NULL
;
2365 cmdline
= exec_command_line(argv
);
2367 *exit_status
= EXIT_CONFIRM
;
2371 r
= ask_for_confirmation(vc
, cmdline
);
2372 if (r
!= CONFIRM_EXECUTE
) {
2373 if (r
== CONFIRM_PRETEND_SUCCESS
) {
2374 *exit_status
= EXIT_SUCCESS
;
2377 *exit_status
= EXIT_CONFIRM
;
2382 if (context
->dynamic_user
&& dcreds
) {
2384 /* Make sure we bypass our own NSS module for any NSS checks */
2385 if (putenv((char*) "SYSTEMD_NSS_DYNAMIC_BYPASS=1") != 0) {
2386 *exit_status
= EXIT_USER
;
2390 r
= dynamic_creds_realize(dcreds
, &uid
, &gid
);
2392 *exit_status
= EXIT_USER
;
2396 if (!uid_is_valid(uid
) || !gid_is_valid(gid
)) {
2397 *exit_status
= EXIT_USER
;
2402 username
= dcreds
->user
->name
;
2405 r
= get_fixed_user(context
, &username
, &uid
, &gid
, &home
, &shell
);
2407 *exit_status
= EXIT_USER
;
2411 r
= get_fixed_group(context
, &groupname
, &gid
);
2413 *exit_status
= EXIT_GROUP
;
2418 /* Initialize user supplementary groups and get SupplementaryGroups= ones */
2419 r
= get_supplementary_groups(context
, username
, groupname
, gid
,
2420 &supplementary_gids
, &ngids
);
2422 *exit_status
= EXIT_GROUP
;
2426 r
= send_user_lookup(unit
, user_lookup_fd
, uid
, gid
);
2428 *exit_status
= EXIT_USER
;
2432 user_lookup_fd
= safe_close(user_lookup_fd
);
2434 /* If a socket is connected to STDIN/STDOUT/STDERR, we
2435 * must sure to drop O_NONBLOCK */
2437 (void) fd_nonblock(socket_fd
, false);
2439 r
= setup_input(context
, params
, socket_fd
, named_iofds
);
2441 *exit_status
= EXIT_STDIN
;
2445 r
= setup_output(unit
, context
, params
, STDOUT_FILENO
, socket_fd
, named_iofds
, basename(command
->path
), uid
, gid
, &journal_stream_dev
, &journal_stream_ino
);
2447 *exit_status
= EXIT_STDOUT
;
2451 r
= setup_output(unit
, context
, params
, STDERR_FILENO
, socket_fd
, named_iofds
, basename(command
->path
), uid
, gid
, &journal_stream_dev
, &journal_stream_ino
);
2453 *exit_status
= EXIT_STDERR
;
2457 if (params
->cgroup_path
) {
2458 r
= cg_attach_everywhere(params
->cgroup_supported
, params
->cgroup_path
, 0, NULL
, NULL
);
2460 *exit_status
= EXIT_CGROUP
;
2465 if (context
->oom_score_adjust_set
) {
2466 char t
[DECIMAL_STR_MAX(context
->oom_score_adjust
)];
2468 /* When we can't make this change due to EPERM, then
2469 * let's silently skip over it. User namespaces
2470 * prohibit write access to this file, and we
2471 * shouldn't trip up over that. */
2473 sprintf(t
, "%i", context
->oom_score_adjust
);
2474 r
= write_string_file("/proc/self/oom_score_adj", t
, 0);
2475 if (r
== -EPERM
|| r
== -EACCES
) {
2477 log_unit_debug_errno(unit
, r
, "Failed to adjust OOM setting, assuming containerized execution, ignoring: %m");
2480 *exit_status
= EXIT_OOM_ADJUST
;
2485 if (context
->nice_set
)
2486 if (setpriority(PRIO_PROCESS
, 0, context
->nice
) < 0) {
2487 *exit_status
= EXIT_NICE
;
2491 if (context
->cpu_sched_set
) {
2492 struct sched_param param
= {
2493 .sched_priority
= context
->cpu_sched_priority
,
2496 r
= sched_setscheduler(0,
2497 context
->cpu_sched_policy
|
2498 (context
->cpu_sched_reset_on_fork
?
2499 SCHED_RESET_ON_FORK
: 0),
2502 *exit_status
= EXIT_SETSCHEDULER
;
2507 if (context
->cpuset
)
2508 if (sched_setaffinity(0, CPU_ALLOC_SIZE(context
->cpuset_ncpus
), context
->cpuset
) < 0) {
2509 *exit_status
= EXIT_CPUAFFINITY
;
2513 if (context
->ioprio_set
)
2514 if (ioprio_set(IOPRIO_WHO_PROCESS
, 0, context
->ioprio
) < 0) {
2515 *exit_status
= EXIT_IOPRIO
;
2519 if (context
->timer_slack_nsec
!= NSEC_INFINITY
)
2520 if (prctl(PR_SET_TIMERSLACK
, context
->timer_slack_nsec
) < 0) {
2521 *exit_status
= EXIT_TIMERSLACK
;
2525 if (context
->personality
!= PERSONALITY_INVALID
)
2526 if (personality(context
->personality
) < 0) {
2527 *exit_status
= EXIT_PERSONALITY
;
2531 if (context
->utmp_id
)
2532 utmp_put_init_process(context
->utmp_id
, getpid(), getsid(0), context
->tty_path
,
2533 context
->utmp_mode
== EXEC_UTMP_INIT
? INIT_PROCESS
:
2534 context
->utmp_mode
== EXEC_UTMP_LOGIN
? LOGIN_PROCESS
:
2536 username
? "root" : context
->user
);
2538 if (context
->user
) {
2539 r
= chown_terminal(STDIN_FILENO
, uid
);
2541 *exit_status
= EXIT_STDIN
;
2546 /* If delegation is enabled we'll pass ownership of the cgroup
2547 * (but only in systemd's own controller hierarchy!) to the
2548 * user of the new process. */
2549 if (params
->cgroup_path
&& context
->user
&& params
->cgroup_delegate
) {
2550 r
= cg_set_task_access(SYSTEMD_CGROUP_CONTROLLER
, params
->cgroup_path
, 0644, uid
, gid
);
2552 *exit_status
= EXIT_CGROUP
;
2557 r
= cg_set_group_access(SYSTEMD_CGROUP_CONTROLLER
, params
->cgroup_path
, 0755, uid
, gid
);
2559 *exit_status
= EXIT_CGROUP
;
2564 if (!strv_isempty(context
->runtime_directory
) && params
->runtime_prefix
) {
2565 r
= setup_runtime_directory(context
, params
, uid
, gid
);
2567 *exit_status
= EXIT_RUNTIME_DIRECTORY
;
2572 r
= build_environment(
2584 *exit_status
= EXIT_MEMORY
;
2588 r
= build_pass_environment(context
, &pass_env
);
2590 *exit_status
= EXIT_MEMORY
;
2594 accum_env
= strv_env_merge(5,
2595 params
->environment
,
2598 context
->environment
,
2602 *exit_status
= EXIT_MEMORY
;
2605 accum_env
= strv_env_clean(accum_env
);
2607 (void) umask(context
->umask
);
2609 if ((params
->flags
& EXEC_APPLY_PERMISSIONS
) && !command
->privileged
) {
2610 if (context
->pam_name
&& username
) {
2611 r
= setup_pam(context
->pam_name
, username
, uid
, gid
, context
->tty_path
, &accum_env
, fds
, n_fds
);
2613 *exit_status
= EXIT_PAM
;
2619 if (context
->private_network
&& runtime
&& runtime
->netns_storage_socket
[0] >= 0) {
2620 r
= setup_netns(runtime
->netns_storage_socket
);
2622 *exit_status
= EXIT_NETWORK
;
2627 needs_mount_namespace
= exec_needs_mount_namespace(context
, params
, runtime
);
2628 if (needs_mount_namespace
) {
2629 r
= apply_mount_namespace(unit
, context
, params
, runtime
);
2631 *exit_status
= EXIT_NAMESPACE
;
2636 /* Apply just after mount namespace setup */
2637 r
= apply_working_directory(context
, params
, home
, needs_mount_namespace
);
2639 *exit_status
= EXIT_CHROOT
;
2643 /* Drop groups as early as possbile */
2644 if ((params
->flags
& EXEC_APPLY_PERMISSIONS
) && !command
->privileged
) {
2645 r
= enforce_groups(context
, gid
, supplementary_gids
, ngids
);
2647 *exit_status
= EXIT_GROUP
;
2653 if ((params
->flags
& EXEC_APPLY_PERMISSIONS
) &&
2654 mac_selinux_use() &&
2655 params
->selinux_context_net
&&
2657 !command
->privileged
) {
2659 r
= mac_selinux_get_child_mls_label(socket_fd
, command
->path
, context
->selinux_context
, &mac_selinux_context_net
);
2661 *exit_status
= EXIT_SELINUX_CONTEXT
;
2667 if ((params
->flags
& EXEC_APPLY_PERMISSIONS
) && context
->private_users
) {
2668 r
= setup_private_users(uid
, gid
);
2670 *exit_status
= EXIT_USER
;
2675 /* We repeat the fd closing here, to make sure that
2676 * nothing is leaked from the PAM modules. Note that
2677 * we are more aggressive this time since socket_fd
2678 * and the netns fds we don't need anymore. The custom
2679 * endpoint fd was needed to upload the policy and can
2680 * now be closed as well. */
2681 r
= close_all_fds(fds
, n_fds
);
2683 r
= shift_fds(fds
, n_fds
);
2685 r
= flags_fds(fds
, n_fds
, context
->non_blocking
);
2687 *exit_status
= EXIT_FDS
;
2691 if ((params
->flags
& EXEC_APPLY_PERMISSIONS
) && !command
->privileged
) {
2693 int secure_bits
= context
->secure_bits
;
2695 for (i
= 0; i
< _RLIMIT_MAX
; i
++) {
2697 if (!context
->rlimit
[i
])
2700 r
= setrlimit_closest(i
, context
->rlimit
[i
]);
2702 *exit_status
= EXIT_LIMITS
;
2707 /* Set the RTPRIO resource limit to 0, but only if nothing else was explicitly requested. */
2708 if (context
->restrict_realtime
&& !context
->rlimit
[RLIMIT_RTPRIO
]) {
2709 if (setrlimit(RLIMIT_RTPRIO
, &RLIMIT_MAKE_CONST(0)) < 0) {
2710 *exit_status
= EXIT_LIMITS
;
2715 if (!cap_test_all(context
->capability_bounding_set
)) {
2716 r
= capability_bounding_set_drop(context
->capability_bounding_set
, false);
2718 *exit_status
= EXIT_CAPABILITIES
;
2723 /* This is done before enforce_user, but ambient set
2724 * does not survive over setresuid() if keep_caps is not set. */
2725 if (context
->capability_ambient_set
!= 0) {
2726 r
= capability_ambient_set_apply(context
->capability_ambient_set
, true);
2728 *exit_status
= EXIT_CAPABILITIES
;
2733 if (context
->user
) {
2734 r
= enforce_user(context
, uid
);
2736 *exit_status
= EXIT_USER
;
2739 if (context
->capability_ambient_set
!= 0) {
2741 /* Fix the ambient capabilities after user change. */
2742 r
= capability_ambient_set_apply(context
->capability_ambient_set
, false);
2744 *exit_status
= EXIT_CAPABILITIES
;
2748 /* If we were asked to change user and ambient capabilities
2749 * were requested, we had to add keep-caps to the securebits
2750 * so that we would maintain the inherited capability set
2751 * through the setresuid(). Make sure that the bit is added
2752 * also to the context secure_bits so that we don't try to
2753 * drop the bit away next. */
2755 secure_bits
|= 1<<SECURE_KEEP_CAPS
;
2759 /* Apply the MAC contexts late, but before seccomp syscall filtering, as those should really be last to
2760 * influence our own codepaths as little as possible. Moreover, applying MAC contexts usually requires
2761 * syscalls that are subject to seccomp filtering, hence should probably be applied before the syscalls
2762 * are restricted. */
2765 if (mac_selinux_use()) {
2766 char *exec_context
= mac_selinux_context_net
?: context
->selinux_context
;
2769 r
= setexeccon(exec_context
);
2771 *exit_status
= EXIT_SELINUX_CONTEXT
;
2778 r
= setup_smack(context
, command
);
2780 *exit_status
= EXIT_SMACK_PROCESS_LABEL
;
2784 #ifdef HAVE_APPARMOR
2785 if (context
->apparmor_profile
&& mac_apparmor_use()) {
2786 r
= aa_change_onexec(context
->apparmor_profile
);
2787 if (r
< 0 && !context
->apparmor_profile_ignore
) {
2788 *exit_status
= EXIT_APPARMOR_PROFILE
;
2794 /* PR_GET_SECUREBITS is not privileged, while
2795 * PR_SET_SECUREBITS is. So to suppress
2796 * potential EPERMs we'll try not to call
2797 * PR_SET_SECUREBITS unless necessary. */
2798 if (prctl(PR_GET_SECUREBITS
) != secure_bits
)
2799 if (prctl(PR_SET_SECUREBITS
, secure_bits
) < 0) {
2800 *exit_status
= EXIT_SECUREBITS
;
2804 if (context_has_no_new_privileges(context
))
2805 if (prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0) < 0) {
2806 *exit_status
= EXIT_NO_NEW_PRIVILEGES
;
2811 if (context_has_address_families(context
)) {
2812 r
= apply_address_families(unit
, context
);
2814 *exit_status
= EXIT_ADDRESS_FAMILIES
;
2819 if (context
->memory_deny_write_execute
) {
2820 r
= apply_memory_deny_write_execute(unit
, context
);
2822 *exit_status
= EXIT_SECCOMP
;
2827 if (context
->restrict_realtime
) {
2828 r
= apply_restrict_realtime(unit
, context
);
2830 *exit_status
= EXIT_SECCOMP
;
2835 r
= apply_restrict_namespaces(unit
, context
);
2837 *exit_status
= EXIT_SECCOMP
;
2841 if (context
->protect_kernel_tunables
) {
2842 r
= apply_protect_sysctl(unit
, context
);
2844 *exit_status
= EXIT_SECCOMP
;
2849 if (context
->protect_kernel_modules
) {
2850 r
= apply_protect_kernel_modules(unit
, context
);
2852 *exit_status
= EXIT_SECCOMP
;
2857 if (context
->private_devices
) {
2858 r
= apply_private_devices(unit
, context
);
2860 *exit_status
= EXIT_SECCOMP
;
2865 /* This really should remain the last step before the execve(), to make sure our own code is unaffected
2866 * by the filter as little as possible. */
2867 if (context_has_syscall_filters(context
)) {
2868 r
= apply_seccomp(unit
, context
);
2870 *exit_status
= EXIT_SECCOMP
;
2877 final_argv
= replace_env_argv(argv
, accum_env
);
2879 *exit_status
= EXIT_MEMORY
;
2883 if (_unlikely_(log_get_max_level() >= LOG_DEBUG
)) {
2884 _cleanup_free_
char *line
;
2886 line
= exec_command_line(final_argv
);
2889 log_struct(LOG_DEBUG
,
2891 "EXECUTABLE=%s", command
->path
,
2892 LOG_UNIT_MESSAGE(unit
, "Executing: %s", line
),
2898 execve(command
->path
, final_argv
, accum_env
);
2899 *exit_status
= EXIT_EXEC
;
2903 int exec_spawn(Unit
*unit
,
2904 ExecCommand
*command
,
2905 const ExecContext
*context
,
2906 const ExecParameters
*params
,
2907 ExecRuntime
*runtime
,
2908 DynamicCreds
*dcreds
,
2911 _cleanup_strv_free_
char **files_env
= NULL
;
2912 int *fds
= NULL
; unsigned n_fds
= 0;
2913 _cleanup_free_
char *line
= NULL
;
2915 int named_iofds
[3] = { -1, -1, -1 };
2924 assert(params
->fds
|| params
->n_fds
<= 0);
2926 if (context
->std_input
== EXEC_INPUT_SOCKET
||
2927 context
->std_output
== EXEC_OUTPUT_SOCKET
||
2928 context
->std_error
== EXEC_OUTPUT_SOCKET
) {
2930 if (params
->n_fds
!= 1) {
2931 log_unit_error(unit
, "Got more than one socket.");
2935 socket_fd
= params
->fds
[0];
2939 n_fds
= params
->n_fds
;
2942 r
= exec_context_named_iofds(unit
, context
, params
, named_iofds
);
2944 return log_unit_error_errno(unit
, r
, "Failed to load a named file descriptor: %m");
2946 r
= exec_context_load_environment(unit
, context
, &files_env
);
2948 return log_unit_error_errno(unit
, r
, "Failed to load environment files: %m");
2950 argv
= params
->argv
?: command
->argv
;
2951 line
= exec_command_line(argv
);
2955 log_struct(LOG_DEBUG
,
2957 LOG_UNIT_MESSAGE(unit
, "About to execute: %s", line
),
2958 "EXECUTABLE=%s", command
->path
,
2962 return log_unit_error_errno(unit
, errno
, "Failed to fork: %m");
2967 r
= exec_child(unit
,
2978 unit
->manager
->user_lookup_fds
[1],
2982 log_struct_errno(LOG_ERR
, r
,
2983 LOG_MESSAGE_ID(SD_MESSAGE_SPAWN_FAILED
),
2985 LOG_UNIT_MESSAGE(unit
, "Failed at step %s spawning %s: %m",
2986 exit_status_to_string(exit_status
, EXIT_STATUS_SYSTEMD
),
2988 "EXECUTABLE=%s", command
->path
,
2995 log_unit_debug(unit
, "Forked %s as "PID_FMT
, command
->path
, pid
);
2997 /* We add the new process to the cgroup both in the child (so
2998 * that we can be sure that no user code is ever executed
2999 * outside of the cgroup) and in the parent (so that we can be
3000 * sure that when we kill the cgroup the process will be
3002 if (params
->cgroup_path
)
3003 (void) cg_attach(SYSTEMD_CGROUP_CONTROLLER
, params
->cgroup_path
, pid
);
3005 exec_status_start(&command
->exec_status
, pid
);
3011 void exec_context_init(ExecContext
*c
) {
3015 c
->ioprio
= IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE
, 0);
3016 c
->cpu_sched_policy
= SCHED_OTHER
;
3017 c
->syslog_priority
= LOG_DAEMON
|LOG_INFO
;
3018 c
->syslog_level_prefix
= true;
3019 c
->ignore_sigpipe
= true;
3020 c
->timer_slack_nsec
= NSEC_INFINITY
;
3021 c
->personality
= PERSONALITY_INVALID
;
3022 c
->runtime_directory_mode
= 0755;
3023 c
->capability_bounding_set
= CAP_ALL
;
3024 c
->restrict_namespaces
= NAMESPACE_FLAGS_ALL
;
3027 void exec_context_done(ExecContext
*c
) {
3032 c
->environment
= strv_free(c
->environment
);
3033 c
->environment_files
= strv_free(c
->environment_files
);
3034 c
->pass_environment
= strv_free(c
->pass_environment
);
3036 for (l
= 0; l
< ELEMENTSOF(c
->rlimit
); l
++)
3037 c
->rlimit
[l
] = mfree(c
->rlimit
[l
]);
3039 for (l
= 0; l
< 3; l
++)
3040 c
->stdio_fdname
[l
] = mfree(c
->stdio_fdname
[l
]);
3042 c
->working_directory
= mfree(c
->working_directory
);
3043 c
->root_directory
= mfree(c
->root_directory
);
3044 c
->tty_path
= mfree(c
->tty_path
);
3045 c
->syslog_identifier
= mfree(c
->syslog_identifier
);
3046 c
->user
= mfree(c
->user
);
3047 c
->group
= mfree(c
->group
);
3049 c
->supplementary_groups
= strv_free(c
->supplementary_groups
);
3051 c
->pam_name
= mfree(c
->pam_name
);
3053 c
->read_only_paths
= strv_free(c
->read_only_paths
);
3054 c
->read_write_paths
= strv_free(c
->read_write_paths
);
3055 c
->inaccessible_paths
= strv_free(c
->inaccessible_paths
);
3058 CPU_FREE(c
->cpuset
);
3060 c
->utmp_id
= mfree(c
->utmp_id
);
3061 c
->selinux_context
= mfree(c
->selinux_context
);
3062 c
->apparmor_profile
= mfree(c
->apparmor_profile
);
3064 c
->syscall_filter
= set_free(c
->syscall_filter
);
3065 c
->syscall_archs
= set_free(c
->syscall_archs
);
3066 c
->address_families
= set_free(c
->address_families
);
3068 c
->runtime_directory
= strv_free(c
->runtime_directory
);
3071 int exec_context_destroy_runtime_directory(ExecContext
*c
, const char *runtime_prefix
) {
3076 if (!runtime_prefix
)
3079 STRV_FOREACH(i
, c
->runtime_directory
) {
3080 _cleanup_free_
char *p
;
3082 p
= strjoin(runtime_prefix
, "/", *i
);
3086 /* We execute this synchronously, since we need to be
3087 * sure this is gone when we start the service
3089 (void) rm_rf(p
, REMOVE_ROOT
);
3095 void exec_command_done(ExecCommand
*c
) {
3098 c
->path
= mfree(c
->path
);
3100 c
->argv
= strv_free(c
->argv
);
3103 void exec_command_done_array(ExecCommand
*c
, unsigned n
) {
3106 for (i
= 0; i
< n
; i
++)
3107 exec_command_done(c
+i
);
3110 ExecCommand
* exec_command_free_list(ExecCommand
*c
) {
3114 LIST_REMOVE(command
, c
, i
);
3115 exec_command_done(i
);
3122 void exec_command_free_array(ExecCommand
**c
, unsigned n
) {
3125 for (i
= 0; i
< n
; i
++)
3126 c
[i
] = exec_command_free_list(c
[i
]);
3129 typedef struct InvalidEnvInfo
{
3134 static void invalid_env(const char *p
, void *userdata
) {
3135 InvalidEnvInfo
*info
= userdata
;
3137 log_unit_error(info
->unit
, "Ignoring invalid environment assignment '%s': %s", p
, info
->path
);
3140 const char* exec_context_fdname(const ExecContext
*c
, int fd_index
) {
3145 if (c
->std_input
!= EXEC_INPUT_NAMED_FD
)
3147 return c
->stdio_fdname
[STDIN_FILENO
] ?: "stdin";
3149 if (c
->std_output
!= EXEC_OUTPUT_NAMED_FD
)
3151 return c
->stdio_fdname
[STDOUT_FILENO
] ?: "stdout";
3153 if (c
->std_error
!= EXEC_OUTPUT_NAMED_FD
)
3155 return c
->stdio_fdname
[STDERR_FILENO
] ?: "stderr";
3161 int exec_context_named_iofds(Unit
*unit
, const ExecContext
*c
, const ExecParameters
*p
, int named_iofds
[3]) {
3162 unsigned i
, targets
;
3163 const char *stdio_fdname
[3];
3168 targets
= (c
->std_input
== EXEC_INPUT_NAMED_FD
) +
3169 (c
->std_output
== EXEC_OUTPUT_NAMED_FD
) +
3170 (c
->std_error
== EXEC_OUTPUT_NAMED_FD
);
3172 for (i
= 0; i
< 3; i
++)
3173 stdio_fdname
[i
] = exec_context_fdname(c
, i
);
3175 for (i
= 0; i
< p
->n_fds
&& targets
> 0; i
++)
3176 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
])) {
3177 named_iofds
[STDIN_FILENO
] = p
->fds
[i
];
3179 } 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
])) {
3180 named_iofds
[STDOUT_FILENO
] = p
->fds
[i
];
3182 } 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
])) {
3183 named_iofds
[STDERR_FILENO
] = p
->fds
[i
];
3187 return (targets
== 0 ? 0 : -ENOENT
);
3190 int exec_context_load_environment(Unit
*unit
, const ExecContext
*c
, char ***l
) {
3191 char **i
, **r
= NULL
;
3196 STRV_FOREACH(i
, c
->environment_files
) {
3199 bool ignore
= false;
3201 _cleanup_globfree_ glob_t pglob
= {};
3211 if (!path_is_absolute(fn
)) {
3219 /* Filename supports globbing, take all matching files */
3221 if (glob(fn
, 0, NULL
, &pglob
) != 0) {
3226 return errno
> 0 ? -errno
: -EINVAL
;
3228 count
= pglob
.gl_pathc
;
3236 for (n
= 0; n
< count
; n
++) {
3237 k
= load_env_file(NULL
, pglob
.gl_pathv
[n
], NULL
, &p
);
3245 /* Log invalid environment variables with filename */
3247 InvalidEnvInfo info
= {
3249 .path
= pglob
.gl_pathv
[n
]
3252 p
= strv_env_clean_with_callback(p
, invalid_env
, &info
);
3260 m
= strv_env_merge(2, r
, p
);
3276 static bool tty_may_match_dev_console(const char *tty
) {
3277 _cleanup_free_
char *active
= NULL
;
3283 if (startswith(tty
, "/dev/"))
3286 /* trivial identity? */
3287 if (streq(tty
, "console"))
3290 console
= resolve_dev_console(&active
);
3291 /* if we could not resolve, assume it may */
3295 /* "tty0" means the active VC, so it may be the same sometimes */
3296 return streq(console
, tty
) || (streq(console
, "tty0") && tty_is_vc(tty
));
3299 bool exec_context_may_touch_console(ExecContext
*ec
) {
3301 return (ec
->tty_reset
||
3303 ec
->tty_vt_disallocate
||
3304 is_terminal_input(ec
->std_input
) ||
3305 is_terminal_output(ec
->std_output
) ||
3306 is_terminal_output(ec
->std_error
)) &&
3307 tty_may_match_dev_console(exec_context_tty_path(ec
));
3310 static void strv_fprintf(FILE *f
, char **l
) {
3316 fprintf(f
, " %s", *g
);
3319 void exec_context_dump(ExecContext
*c
, FILE* f
, const char *prefix
) {
3327 prefix
= strempty(prefix
);
3331 "%sWorkingDirectory: %s\n"
3332 "%sRootDirectory: %s\n"
3333 "%sNonBlocking: %s\n"
3334 "%sPrivateTmp: %s\n"
3335 "%sPrivateDevices: %s\n"
3336 "%sProtectKernelTunables: %s\n"
3337 "%sProtectKernelModules: %s\n"
3338 "%sProtectControlGroups: %s\n"
3339 "%sPrivateNetwork: %s\n"
3340 "%sPrivateUsers: %s\n"
3341 "%sProtectHome: %s\n"
3342 "%sProtectSystem: %s\n"
3343 "%sIgnoreSIGPIPE: %s\n"
3344 "%sMemoryDenyWriteExecute: %s\n"
3345 "%sRestrictRealtime: %s\n",
3347 prefix
, c
->working_directory
? c
->working_directory
: "/",
3348 prefix
, c
->root_directory
? c
->root_directory
: "/",
3349 prefix
, yes_no(c
->non_blocking
),
3350 prefix
, yes_no(c
->private_tmp
),
3351 prefix
, yes_no(c
->private_devices
),
3352 prefix
, yes_no(c
->protect_kernel_tunables
),
3353 prefix
, yes_no(c
->protect_kernel_modules
),
3354 prefix
, yes_no(c
->protect_control_groups
),
3355 prefix
, yes_no(c
->private_network
),
3356 prefix
, yes_no(c
->private_users
),
3357 prefix
, protect_home_to_string(c
->protect_home
),
3358 prefix
, protect_system_to_string(c
->protect_system
),
3359 prefix
, yes_no(c
->ignore_sigpipe
),
3360 prefix
, yes_no(c
->memory_deny_write_execute
),
3361 prefix
, yes_no(c
->restrict_realtime
));
3363 STRV_FOREACH(e
, c
->environment
)
3364 fprintf(f
, "%sEnvironment: %s\n", prefix
, *e
);
3366 STRV_FOREACH(e
, c
->environment_files
)
3367 fprintf(f
, "%sEnvironmentFile: %s\n", prefix
, *e
);
3369 STRV_FOREACH(e
, c
->pass_environment
)
3370 fprintf(f
, "%sPassEnvironment: %s\n", prefix
, *e
);
3372 fprintf(f
, "%sRuntimeDirectoryMode: %04o\n", prefix
, c
->runtime_directory_mode
);
3374 STRV_FOREACH(d
, c
->runtime_directory
)
3375 fprintf(f
, "%sRuntimeDirectory: %s\n", prefix
, *d
);
3382 if (c
->oom_score_adjust_set
)
3384 "%sOOMScoreAdjust: %i\n",
3385 prefix
, c
->oom_score_adjust
);
3387 for (i
= 0; i
< RLIM_NLIMITS
; i
++)
3389 fprintf(f
, "%s%s: " RLIM_FMT
"\n",
3390 prefix
, rlimit_to_string(i
), c
->rlimit
[i
]->rlim_max
);
3391 fprintf(f
, "%s%sSoft: " RLIM_FMT
"\n",
3392 prefix
, rlimit_to_string(i
), c
->rlimit
[i
]->rlim_cur
);
3395 if (c
->ioprio_set
) {
3396 _cleanup_free_
char *class_str
= NULL
;
3398 ioprio_class_to_string_alloc(IOPRIO_PRIO_CLASS(c
->ioprio
), &class_str
);
3400 "%sIOSchedulingClass: %s\n"
3401 "%sIOPriority: %i\n",
3402 prefix
, strna(class_str
),
3403 prefix
, (int) IOPRIO_PRIO_DATA(c
->ioprio
));
3406 if (c
->cpu_sched_set
) {
3407 _cleanup_free_
char *policy_str
= NULL
;
3409 sched_policy_to_string_alloc(c
->cpu_sched_policy
, &policy_str
);
3411 "%sCPUSchedulingPolicy: %s\n"
3412 "%sCPUSchedulingPriority: %i\n"
3413 "%sCPUSchedulingResetOnFork: %s\n",
3414 prefix
, strna(policy_str
),
3415 prefix
, c
->cpu_sched_priority
,
3416 prefix
, yes_no(c
->cpu_sched_reset_on_fork
));
3420 fprintf(f
, "%sCPUAffinity:", prefix
);
3421 for (i
= 0; i
< c
->cpuset_ncpus
; i
++)
3422 if (CPU_ISSET_S(i
, CPU_ALLOC_SIZE(c
->cpuset_ncpus
), c
->cpuset
))
3423 fprintf(f
, " %u", i
);
3427 if (c
->timer_slack_nsec
!= NSEC_INFINITY
)
3428 fprintf(f
, "%sTimerSlackNSec: "NSEC_FMT
"\n", prefix
, c
->timer_slack_nsec
);
3431 "%sStandardInput: %s\n"
3432 "%sStandardOutput: %s\n"
3433 "%sStandardError: %s\n",
3434 prefix
, exec_input_to_string(c
->std_input
),
3435 prefix
, exec_output_to_string(c
->std_output
),
3436 prefix
, exec_output_to_string(c
->std_error
));
3442 "%sTTYVHangup: %s\n"
3443 "%sTTYVTDisallocate: %s\n",
3444 prefix
, c
->tty_path
,
3445 prefix
, yes_no(c
->tty_reset
),
3446 prefix
, yes_no(c
->tty_vhangup
),
3447 prefix
, yes_no(c
->tty_vt_disallocate
));
3449 if (c
->std_output
== EXEC_OUTPUT_SYSLOG
||
3450 c
->std_output
== EXEC_OUTPUT_KMSG
||
3451 c
->std_output
== EXEC_OUTPUT_JOURNAL
||
3452 c
->std_output
== EXEC_OUTPUT_SYSLOG_AND_CONSOLE
||
3453 c
->std_output
== EXEC_OUTPUT_KMSG_AND_CONSOLE
||
3454 c
->std_output
== EXEC_OUTPUT_JOURNAL_AND_CONSOLE
||
3455 c
->std_error
== EXEC_OUTPUT_SYSLOG
||
3456 c
->std_error
== EXEC_OUTPUT_KMSG
||
3457 c
->std_error
== EXEC_OUTPUT_JOURNAL
||
3458 c
->std_error
== EXEC_OUTPUT_SYSLOG_AND_CONSOLE
||
3459 c
->std_error
== EXEC_OUTPUT_KMSG_AND_CONSOLE
||
3460 c
->std_error
== EXEC_OUTPUT_JOURNAL_AND_CONSOLE
) {
3462 _cleanup_free_
char *fac_str
= NULL
, *lvl_str
= NULL
;
3464 log_facility_unshifted_to_string_alloc(c
->syslog_priority
>> 3, &fac_str
);
3465 log_level_to_string_alloc(LOG_PRI(c
->syslog_priority
), &lvl_str
);
3468 "%sSyslogFacility: %s\n"
3469 "%sSyslogLevel: %s\n",
3470 prefix
, strna(fac_str
),
3471 prefix
, strna(lvl_str
));
3475 fprintf(f
, "%sSecure Bits:%s%s%s%s%s%s\n",
3477 (c
->secure_bits
& 1<<SECURE_KEEP_CAPS
) ? " keep-caps" : "",
3478 (c
->secure_bits
& 1<<SECURE_KEEP_CAPS_LOCKED
) ? " keep-caps-locked" : "",
3479 (c
->secure_bits
& 1<<SECURE_NO_SETUID_FIXUP
) ? " no-setuid-fixup" : "",
3480 (c
->secure_bits
& 1<<SECURE_NO_SETUID_FIXUP_LOCKED
) ? " no-setuid-fixup-locked" : "",
3481 (c
->secure_bits
& 1<<SECURE_NOROOT
) ? " noroot" : "",
3482 (c
->secure_bits
& 1<<SECURE_NOROOT_LOCKED
) ? "noroot-locked" : "");
3484 if (c
->capability_bounding_set
!= CAP_ALL
) {
3486 fprintf(f
, "%sCapabilityBoundingSet:", prefix
);
3488 for (l
= 0; l
<= cap_last_cap(); l
++)
3489 if (c
->capability_bounding_set
& (UINT64_C(1) << l
))
3490 fprintf(f
, " %s", strna(capability_to_name(l
)));
3495 if (c
->capability_ambient_set
!= 0) {
3497 fprintf(f
, "%sAmbientCapabilities:", prefix
);
3499 for (l
= 0; l
<= cap_last_cap(); l
++)
3500 if (c
->capability_ambient_set
& (UINT64_C(1) << l
))
3501 fprintf(f
, " %s", strna(capability_to_name(l
)));
3507 fprintf(f
, "%sUser: %s\n", prefix
, c
->user
);
3509 fprintf(f
, "%sGroup: %s\n", prefix
, c
->group
);
3511 fprintf(f
, "%sDynamicUser: %s\n", prefix
, yes_no(c
->dynamic_user
));
3513 if (strv_length(c
->supplementary_groups
) > 0) {
3514 fprintf(f
, "%sSupplementaryGroups:", prefix
);
3515 strv_fprintf(f
, c
->supplementary_groups
);
3520 fprintf(f
, "%sPAMName: %s\n", prefix
, c
->pam_name
);
3522 if (strv_length(c
->read_write_paths
) > 0) {
3523 fprintf(f
, "%sReadWritePaths:", prefix
);
3524 strv_fprintf(f
, c
->read_write_paths
);
3528 if (strv_length(c
->read_only_paths
) > 0) {
3529 fprintf(f
, "%sReadOnlyPaths:", prefix
);
3530 strv_fprintf(f
, c
->read_only_paths
);
3534 if (strv_length(c
->inaccessible_paths
) > 0) {
3535 fprintf(f
, "%sInaccessiblePaths:", prefix
);
3536 strv_fprintf(f
, c
->inaccessible_paths
);
3542 "%sUtmpIdentifier: %s\n",
3543 prefix
, c
->utmp_id
);
3545 if (c
->selinux_context
)
3547 "%sSELinuxContext: %s%s\n",
3548 prefix
, c
->selinux_context_ignore
? "-" : "", c
->selinux_context
);
3550 if (c
->personality
!= PERSONALITY_INVALID
)
3552 "%sPersonality: %s\n",
3553 prefix
, strna(personality_to_string(c
->personality
)));
3555 if (c
->syscall_filter
) {
3563 "%sSystemCallFilter: ",
3566 if (!c
->syscall_whitelist
)
3570 SET_FOREACH(id
, c
->syscall_filter
, j
) {
3571 _cleanup_free_
char *name
= NULL
;
3578 name
= seccomp_syscall_resolve_num_arch(SCMP_ARCH_NATIVE
, PTR_TO_INT(id
) - 1);
3579 fputs(strna(name
), f
);
3586 if (c
->syscall_archs
) {
3593 "%sSystemCallArchitectures:",
3597 SET_FOREACH(id
, c
->syscall_archs
, j
)
3598 fprintf(f
, " %s", strna(seccomp_arch_to_string(PTR_TO_UINT32(id
) - 1)));
3603 if (exec_context_restrict_namespaces_set(c
)) {
3604 _cleanup_free_
char *s
= NULL
;
3606 r
= namespace_flag_to_string_many(c
->restrict_namespaces
, &s
);
3608 fprintf(f
, "%sRestrictNamespaces: %s\n",
3612 if (c
->syscall_errno
> 0)
3614 "%sSystemCallErrorNumber: %s\n",
3615 prefix
, strna(errno_to_name(c
->syscall_errno
)));
3617 if (c
->apparmor_profile
)
3619 "%sAppArmorProfile: %s%s\n",
3620 prefix
, c
->apparmor_profile_ignore
? "-" : "", c
->apparmor_profile
);
3623 bool exec_context_maintains_privileges(ExecContext
*c
) {
3626 /* Returns true if the process forked off would run under
3627 * an unchanged UID or as root. */
3632 if (streq(c
->user
, "root") || streq(c
->user
, "0"))
3638 void exec_status_start(ExecStatus
*s
, pid_t pid
) {
3643 dual_timestamp_get(&s
->start_timestamp
);
3646 void exec_status_exit(ExecStatus
*s
, ExecContext
*context
, pid_t pid
, int code
, int status
) {
3649 if (s
->pid
&& s
->pid
!= pid
)
3653 dual_timestamp_get(&s
->exit_timestamp
);
3659 if (context
->utmp_id
)
3660 utmp_put_dead_process(context
->utmp_id
, pid
, code
, status
);
3662 exec_context_tty_reset(context
, NULL
);
3666 void exec_status_dump(ExecStatus
*s
, FILE *f
, const char *prefix
) {
3667 char buf
[FORMAT_TIMESTAMP_MAX
];
3675 prefix
= strempty(prefix
);
3678 "%sPID: "PID_FMT
"\n",
3681 if (dual_timestamp_is_set(&s
->start_timestamp
))
3683 "%sStart Timestamp: %s\n",
3684 prefix
, format_timestamp(buf
, sizeof(buf
), s
->start_timestamp
.realtime
));
3686 if (dual_timestamp_is_set(&s
->exit_timestamp
))
3688 "%sExit Timestamp: %s\n"
3690 "%sExit Status: %i\n",
3691 prefix
, format_timestamp(buf
, sizeof(buf
), s
->exit_timestamp
.realtime
),
3692 prefix
, sigchld_code_to_string(s
->code
),
3696 char *exec_command_line(char **argv
) {
3704 STRV_FOREACH(a
, argv
)
3712 STRV_FOREACH(a
, argv
) {
3719 if (strpbrk(*a
, WHITESPACE
)) {
3730 /* FIXME: this doesn't really handle arguments that have
3731 * spaces and ticks in them */
3736 void exec_command_dump(ExecCommand
*c
, FILE *f
, const char *prefix
) {
3737 _cleanup_free_
char *cmd
= NULL
;
3738 const char *prefix2
;
3743 prefix
= strempty(prefix
);
3744 prefix2
= strjoina(prefix
, "\t");
3746 cmd
= exec_command_line(c
->argv
);
3748 "%sCommand Line: %s\n",
3749 prefix
, cmd
? cmd
: strerror(ENOMEM
));
3751 exec_status_dump(&c
->exec_status
, f
, prefix2
);
3754 void exec_command_dump_list(ExecCommand
*c
, FILE *f
, const char *prefix
) {
3757 prefix
= strempty(prefix
);
3759 LIST_FOREACH(command
, c
, c
)
3760 exec_command_dump(c
, f
, prefix
);
3763 void exec_command_append_list(ExecCommand
**l
, ExecCommand
*e
) {
3770 /* It's kind of important, that we keep the order here */
3771 LIST_FIND_TAIL(command
, *l
, end
);
3772 LIST_INSERT_AFTER(command
, *l
, end
, e
);
3777 int exec_command_set(ExecCommand
*c
, const char *path
, ...) {
3785 l
= strv_new_ap(path
, ap
);
3806 int exec_command_append(ExecCommand
*c
, const char *path
, ...) {
3807 _cleanup_strv_free_
char **l
= NULL
;
3815 l
= strv_new_ap(path
, ap
);
3821 r
= strv_extend_strv(&c
->argv
, l
, false);
3829 static int exec_runtime_allocate(ExecRuntime
**rt
) {
3834 *rt
= new0(ExecRuntime
, 1);
3839 (*rt
)->netns_storage_socket
[0] = (*rt
)->netns_storage_socket
[1] = -1;
3844 int exec_runtime_make(ExecRuntime
**rt
, ExecContext
*c
, const char *id
) {
3854 if (!c
->private_network
&& !c
->private_tmp
)
3857 r
= exec_runtime_allocate(rt
);
3861 if (c
->private_network
&& (*rt
)->netns_storage_socket
[0] < 0) {
3862 if (socketpair(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
, 0, (*rt
)->netns_storage_socket
) < 0)
3866 if (c
->private_tmp
&& !(*rt
)->tmp_dir
) {
3867 r
= setup_tmp_dirs(id
, &(*rt
)->tmp_dir
, &(*rt
)->var_tmp_dir
);
3875 ExecRuntime
*exec_runtime_ref(ExecRuntime
*r
) {
3877 assert(r
->n_ref
> 0);
3883 ExecRuntime
*exec_runtime_unref(ExecRuntime
*r
) {
3888 assert(r
->n_ref
> 0);
3895 free(r
->var_tmp_dir
);
3896 safe_close_pair(r
->netns_storage_socket
);
3900 int exec_runtime_serialize(Unit
*u
, ExecRuntime
*rt
, FILE *f
, FDSet
*fds
) {
3909 unit_serialize_item(u
, f
, "tmp-dir", rt
->tmp_dir
);
3911 if (rt
->var_tmp_dir
)
3912 unit_serialize_item(u
, f
, "var-tmp-dir", rt
->var_tmp_dir
);
3914 if (rt
->netns_storage_socket
[0] >= 0) {
3917 copy
= fdset_put_dup(fds
, rt
->netns_storage_socket
[0]);
3921 unit_serialize_item_format(u
, f
, "netns-socket-0", "%i", copy
);
3924 if (rt
->netns_storage_socket
[1] >= 0) {
3927 copy
= fdset_put_dup(fds
, rt
->netns_storage_socket
[1]);
3931 unit_serialize_item_format(u
, f
, "netns-socket-1", "%i", copy
);
3937 int exec_runtime_deserialize_item(Unit
*u
, ExecRuntime
**rt
, const char *key
, const char *value
, FDSet
*fds
) {
3944 if (streq(key
, "tmp-dir")) {
3947 r
= exec_runtime_allocate(rt
);
3951 copy
= strdup(value
);
3955 free((*rt
)->tmp_dir
);
3956 (*rt
)->tmp_dir
= copy
;
3958 } else if (streq(key
, "var-tmp-dir")) {
3961 r
= exec_runtime_allocate(rt
);
3965 copy
= strdup(value
);
3969 free((*rt
)->var_tmp_dir
);
3970 (*rt
)->var_tmp_dir
= copy
;
3972 } else if (streq(key
, "netns-socket-0")) {
3975 r
= exec_runtime_allocate(rt
);
3979 if (safe_atoi(value
, &fd
) < 0 || !fdset_contains(fds
, fd
))
3980 log_unit_debug(u
, "Failed to parse netns socket value: %s", value
);
3982 safe_close((*rt
)->netns_storage_socket
[0]);
3983 (*rt
)->netns_storage_socket
[0] = fdset_remove(fds
, fd
);
3985 } else if (streq(key
, "netns-socket-1")) {
3988 r
= exec_runtime_allocate(rt
);
3992 if (safe_atoi(value
, &fd
) < 0 || !fdset_contains(fds
, fd
))
3993 log_unit_debug(u
, "Failed to parse netns socket value: %s", value
);
3995 safe_close((*rt
)->netns_storage_socket
[1]);
3996 (*rt
)->netns_storage_socket
[1] = fdset_remove(fds
, fd
);
4004 static void *remove_tmpdir_thread(void *p
) {
4005 _cleanup_free_
char *path
= p
;
4007 (void) rm_rf(path
, REMOVE_ROOT
|REMOVE_PHYSICAL
);
4011 void exec_runtime_destroy(ExecRuntime
*rt
) {
4017 /* If there are multiple users of this, let's leave the stuff around */
4022 log_debug("Spawning thread to nuke %s", rt
->tmp_dir
);
4024 r
= asynchronous_job(remove_tmpdir_thread
, rt
->tmp_dir
);
4026 log_warning_errno(r
, "Failed to nuke %s: %m", rt
->tmp_dir
);
4033 if (rt
->var_tmp_dir
) {
4034 log_debug("Spawning thread to nuke %s", rt
->var_tmp_dir
);
4036 r
= asynchronous_job(remove_tmpdir_thread
, rt
->var_tmp_dir
);
4038 log_warning_errno(r
, "Failed to nuke %s: %m", rt
->var_tmp_dir
);
4039 free(rt
->var_tmp_dir
);
4042 rt
->var_tmp_dir
= NULL
;
4045 safe_close_pair(rt
->netns_storage_socket
);
4048 static const char* const exec_input_table
[_EXEC_INPUT_MAX
] = {
4049 [EXEC_INPUT_NULL
] = "null",
4050 [EXEC_INPUT_TTY
] = "tty",
4051 [EXEC_INPUT_TTY_FORCE
] = "tty-force",
4052 [EXEC_INPUT_TTY_FAIL
] = "tty-fail",
4053 [EXEC_INPUT_SOCKET
] = "socket",
4054 [EXEC_INPUT_NAMED_FD
] = "fd",
4057 DEFINE_STRING_TABLE_LOOKUP(exec_input
, ExecInput
);
4059 static const char* const exec_output_table
[_EXEC_OUTPUT_MAX
] = {
4060 [EXEC_OUTPUT_INHERIT
] = "inherit",
4061 [EXEC_OUTPUT_NULL
] = "null",
4062 [EXEC_OUTPUT_TTY
] = "tty",
4063 [EXEC_OUTPUT_SYSLOG
] = "syslog",
4064 [EXEC_OUTPUT_SYSLOG_AND_CONSOLE
] = "syslog+console",
4065 [EXEC_OUTPUT_KMSG
] = "kmsg",
4066 [EXEC_OUTPUT_KMSG_AND_CONSOLE
] = "kmsg+console",
4067 [EXEC_OUTPUT_JOURNAL
] = "journal",
4068 [EXEC_OUTPUT_JOURNAL_AND_CONSOLE
] = "journal+console",
4069 [EXEC_OUTPUT_SOCKET
] = "socket",
4070 [EXEC_OUTPUT_NAMED_FD
] = "fd",
4073 DEFINE_STRING_TABLE_LOOKUP(exec_output
, ExecOutput
);
4075 static const char* const exec_utmp_mode_table
[_EXEC_UTMP_MODE_MAX
] = {
4076 [EXEC_UTMP_INIT
] = "init",
4077 [EXEC_UTMP_LOGIN
] = "login",
4078 [EXEC_UTMP_USER
] = "user",
4081 DEFINE_STRING_TABLE_LOOKUP(exec_utmp_mode
, ExecUtmpMode
);