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>
32 #include <sys/socket.h>
39 #include <security/pam_appl.h>
43 #include <selinux/selinux.h>
51 #include <sys/apparmor.h>
54 #include "sd-messages.h"
57 #include "alloc-util.h"
59 #include "apparmor-util.h"
64 #include "capability-util.h"
67 #include "errno-list.h"
69 #include "exit-status.h"
72 #include "formats-util.h"
74 #include "glob-util.h"
81 #include "namespace.h"
82 #include "parse-util.h"
83 #include "path-util.h"
84 #include "process-util.h"
85 #include "rlimit-util.h"
88 #include "seccomp-util.h"
90 #include "securebits.h"
91 #include "selinux-util.h"
92 #include "signal-util.h"
93 #include "smack-util.h"
95 #include "string-table.h"
96 #include "string-util.h"
98 #include "syslog-util.h"
99 #include "terminal-util.h"
101 #include "user-util.h"
103 #include "utmp-wtmp.h"
105 #define IDLE_TIMEOUT_USEC (5*USEC_PER_SEC)
106 #define IDLE_TIMEOUT2_USEC (1*USEC_PER_SEC)
108 /* This assumes there is a 'tty' group */
109 #define TTY_MODE 0620
111 #define SNDBUF_SIZE (8*1024*1024)
113 static int shift_fds(int fds
[], unsigned n_fds
) {
114 int start
, restart_from
;
119 /* Modifies the fds array! (sorts it) */
129 for (i
= start
; i
< (int) n_fds
; i
++) {
132 /* Already at right index? */
136 nfd
= fcntl(fds
[i
], F_DUPFD
, i
+ 3);
143 /* Hmm, the fd we wanted isn't free? Then
144 * let's remember that and try again from here */
145 if (nfd
!= i
+3 && restart_from
< 0)
149 if (restart_from
< 0)
152 start
= restart_from
;
158 static int flags_fds(const int fds
[], unsigned n_fds
, bool nonblock
) {
167 /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags */
169 for (i
= 0; i
< n_fds
; i
++) {
171 r
= fd_nonblock(fds
[i
], nonblock
);
175 /* We unconditionally drop FD_CLOEXEC from the fds,
176 * since after all we want to pass these fds to our
179 r
= fd_cloexec(fds
[i
], false);
187 static const char *exec_context_tty_path(const ExecContext
*context
) {
190 if (context
->stdio_as_fds
)
193 if (context
->tty_path
)
194 return context
->tty_path
;
196 return "/dev/console";
199 static void exec_context_tty_reset(const ExecContext
*context
, const ExecParameters
*p
) {
204 path
= exec_context_tty_path(context
);
206 if (context
->tty_vhangup
) {
207 if (p
&& p
->stdin_fd
>= 0)
208 (void) terminal_vhangup_fd(p
->stdin_fd
);
210 (void) terminal_vhangup(path
);
213 if (context
->tty_reset
) {
214 if (p
&& p
->stdin_fd
>= 0)
215 (void) reset_terminal_fd(p
->stdin_fd
, true);
217 (void) reset_terminal(path
);
220 if (context
->tty_vt_disallocate
&& path
)
221 (void) vt_disallocate(path
);
224 static bool is_terminal_input(ExecInput i
) {
227 EXEC_INPUT_TTY_FORCE
,
228 EXEC_INPUT_TTY_FAIL
);
231 static bool is_terminal_output(ExecOutput o
) {
234 EXEC_OUTPUT_SYSLOG_AND_CONSOLE
,
235 EXEC_OUTPUT_KMSG_AND_CONSOLE
,
236 EXEC_OUTPUT_JOURNAL_AND_CONSOLE
);
239 static bool exec_context_needs_term(const ExecContext
*c
) {
242 /* Return true if the execution context suggests we should set $TERM to something useful. */
244 if (is_terminal_input(c
->std_input
))
247 if (is_terminal_output(c
->std_output
))
250 if (is_terminal_output(c
->std_error
))
253 return !!c
->tty_path
;
256 static int open_null_as(int flags
, int nfd
) {
261 fd
= open("/dev/null", flags
|O_NOCTTY
);
266 r
= dup2(fd
, nfd
) < 0 ? -errno
: nfd
;
274 static int connect_journal_socket(int fd
, uid_t uid
, gid_t gid
) {
275 union sockaddr_union sa
= {
276 .un
.sun_family
= AF_UNIX
,
277 .un
.sun_path
= "/run/systemd/journal/stdout",
279 uid_t olduid
= UID_INVALID
;
280 gid_t oldgid
= GID_INVALID
;
283 if (gid
!= GID_INVALID
) {
291 if (uid
!= UID_INVALID
) {
301 r
= connect(fd
, &sa
.sa
, SOCKADDR_UN_LEN(sa
.un
));
305 /* If we fail to restore the uid or gid, things will likely
306 fail later on. This should only happen if an LSM interferes. */
308 if (uid
!= UID_INVALID
)
309 (void) seteuid(olduid
);
312 if (gid
!= GID_INVALID
)
313 (void) setegid(oldgid
);
318 static int connect_logger_as(
320 const ExecContext
*context
,
330 assert(output
< _EXEC_OUTPUT_MAX
);
334 fd
= socket(AF_UNIX
, SOCK_STREAM
, 0);
338 r
= connect_journal_socket(fd
, uid
, gid
);
342 if (shutdown(fd
, SHUT_RD
) < 0) {
347 (void) fd_inc_sndbuf(fd
, SNDBUF_SIZE
);
357 context
->syslog_identifier
? context
->syslog_identifier
: ident
,
359 context
->syslog_priority
,
360 !!context
->syslog_level_prefix
,
361 output
== EXEC_OUTPUT_SYSLOG
|| output
== EXEC_OUTPUT_SYSLOG_AND_CONSOLE
,
362 output
== EXEC_OUTPUT_KMSG
|| output
== EXEC_OUTPUT_KMSG_AND_CONSOLE
,
363 is_terminal_output(output
));
368 r
= dup2(fd
, nfd
) < 0 ? -errno
: nfd
;
373 static int open_terminal_as(const char *path
, mode_t mode
, int nfd
) {
379 fd
= open_terminal(path
, mode
| O_NOCTTY
);
384 r
= dup2(fd
, nfd
) < 0 ? -errno
: nfd
;
392 static int fixup_input(ExecInput std_input
, int socket_fd
, bool apply_tty_stdin
) {
394 if (is_terminal_input(std_input
) && !apply_tty_stdin
)
395 return EXEC_INPUT_NULL
;
397 if (std_input
== EXEC_INPUT_SOCKET
&& socket_fd
< 0)
398 return EXEC_INPUT_NULL
;
403 static int fixup_output(ExecOutput std_output
, int socket_fd
) {
405 if (std_output
== EXEC_OUTPUT_SOCKET
&& socket_fd
< 0)
406 return EXEC_OUTPUT_INHERIT
;
411 static int setup_input(
412 const ExecContext
*context
,
413 const ExecParameters
*params
,
421 if (params
->stdin_fd
>= 0) {
422 if (dup2(params
->stdin_fd
, STDIN_FILENO
) < 0)
425 /* Try to make this the controlling tty, if it is a tty, and reset it */
426 (void) ioctl(STDIN_FILENO
, TIOCSCTTY
, context
->std_input
== EXEC_INPUT_TTY_FORCE
);
427 (void) reset_terminal_fd(STDIN_FILENO
, true);
432 i
= fixup_input(context
->std_input
, socket_fd
, params
->flags
& EXEC_APPLY_TTY_STDIN
);
436 case EXEC_INPUT_NULL
:
437 return open_null_as(O_RDONLY
, STDIN_FILENO
);
440 case EXEC_INPUT_TTY_FORCE
:
441 case EXEC_INPUT_TTY_FAIL
: {
444 fd
= acquire_terminal(exec_context_tty_path(context
),
445 i
== EXEC_INPUT_TTY_FAIL
,
446 i
== EXEC_INPUT_TTY_FORCE
,
452 if (fd
!= STDIN_FILENO
) {
453 r
= dup2(fd
, STDIN_FILENO
) < 0 ? -errno
: STDIN_FILENO
;
461 case EXEC_INPUT_SOCKET
:
462 return dup2(socket_fd
, STDIN_FILENO
) < 0 ? -errno
: STDIN_FILENO
;
465 assert_not_reached("Unknown input type");
469 static int setup_output(
471 const ExecContext
*context
,
472 const ExecParameters
*params
,
478 dev_t
*journal_stream_dev
,
479 ino_t
*journal_stream_ino
) {
489 assert(journal_stream_dev
);
490 assert(journal_stream_ino
);
492 if (fileno
== STDOUT_FILENO
&& params
->stdout_fd
>= 0) {
494 if (dup2(params
->stdout_fd
, STDOUT_FILENO
) < 0)
497 return STDOUT_FILENO
;
500 if (fileno
== STDERR_FILENO
&& params
->stderr_fd
>= 0) {
501 if (dup2(params
->stderr_fd
, STDERR_FILENO
) < 0)
504 return STDERR_FILENO
;
507 i
= fixup_input(context
->std_input
, socket_fd
, params
->flags
& EXEC_APPLY_TTY_STDIN
);
508 o
= fixup_output(context
->std_output
, socket_fd
);
510 if (fileno
== STDERR_FILENO
) {
512 e
= fixup_output(context
->std_error
, socket_fd
);
514 /* This expects the input and output are already set up */
516 /* Don't change the stderr file descriptor if we inherit all
517 * the way and are not on a tty */
518 if (e
== EXEC_OUTPUT_INHERIT
&&
519 o
== EXEC_OUTPUT_INHERIT
&&
520 i
== EXEC_INPUT_NULL
&&
521 !is_terminal_input(context
->std_input
) &&
525 /* Duplicate from stdout if possible */
526 if (e
== o
|| e
== EXEC_OUTPUT_INHERIT
)
527 return dup2(STDOUT_FILENO
, fileno
) < 0 ? -errno
: fileno
;
531 } else if (o
== EXEC_OUTPUT_INHERIT
) {
532 /* If input got downgraded, inherit the original value */
533 if (i
== EXEC_INPUT_NULL
&& is_terminal_input(context
->std_input
))
534 return open_terminal_as(exec_context_tty_path(context
), O_WRONLY
, fileno
);
536 /* If the input is connected to anything that's not a /dev/null, inherit that... */
537 if (i
!= EXEC_INPUT_NULL
)
538 return dup2(STDIN_FILENO
, fileno
) < 0 ? -errno
: fileno
;
540 /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */
544 /* We need to open /dev/null here anew, to get the right access mode. */
545 return open_null_as(O_WRONLY
, fileno
);
550 case EXEC_OUTPUT_NULL
:
551 return open_null_as(O_WRONLY
, fileno
);
553 case EXEC_OUTPUT_TTY
:
554 if (is_terminal_input(i
))
555 return dup2(STDIN_FILENO
, fileno
) < 0 ? -errno
: fileno
;
557 /* We don't reset the terminal if this is just about output */
558 return open_terminal_as(exec_context_tty_path(context
), O_WRONLY
, fileno
);
560 case EXEC_OUTPUT_SYSLOG
:
561 case EXEC_OUTPUT_SYSLOG_AND_CONSOLE
:
562 case EXEC_OUTPUT_KMSG
:
563 case EXEC_OUTPUT_KMSG_AND_CONSOLE
:
564 case EXEC_OUTPUT_JOURNAL
:
565 case EXEC_OUTPUT_JOURNAL_AND_CONSOLE
:
566 r
= connect_logger_as(unit
, context
, o
, ident
, fileno
, uid
, gid
);
568 log_unit_error_errno(unit
, r
, "Failed to connect %s to the journal socket, ignoring: %m", fileno
== STDOUT_FILENO
? "stdout" : "stderr");
569 r
= open_null_as(O_WRONLY
, fileno
);
573 /* If we connected this fd to the journal via a stream, patch the device/inode into the passed
574 * parameters, but only then. This is useful so that we can set $JOURNAL_STREAM that permits
575 * services to detect whether they are connected to the journal or not. */
577 if (fstat(fileno
, &st
) >= 0) {
578 *journal_stream_dev
= st
.st_dev
;
579 *journal_stream_ino
= st
.st_ino
;
584 case EXEC_OUTPUT_SOCKET
:
585 assert(socket_fd
>= 0);
586 return dup2(socket_fd
, fileno
) < 0 ? -errno
: fileno
;
589 assert_not_reached("Unknown error type");
593 static int chown_terminal(int fd
, uid_t uid
) {
598 /* Before we chown/chmod the TTY, let's ensure this is actually a tty */
602 /* This might fail. What matters are the results. */
603 (void) fchown(fd
, uid
, -1);
604 (void) fchmod(fd
, TTY_MODE
);
606 if (fstat(fd
, &st
) < 0)
609 if (st
.st_uid
!= uid
|| (st
.st_mode
& 0777) != TTY_MODE
)
615 static int setup_confirm_stdio(int *_saved_stdin
, int *_saved_stdout
) {
616 _cleanup_close_
int fd
= -1, saved_stdin
= -1, saved_stdout
= -1;
619 assert(_saved_stdin
);
620 assert(_saved_stdout
);
622 saved_stdin
= fcntl(STDIN_FILENO
, F_DUPFD
, 3);
626 saved_stdout
= fcntl(STDOUT_FILENO
, F_DUPFD
, 3);
627 if (saved_stdout
< 0)
630 fd
= acquire_terminal(
635 DEFAULT_CONFIRM_USEC
);
639 r
= chown_terminal(fd
, getuid());
643 r
= reset_terminal_fd(fd
, true);
647 if (dup2(fd
, STDIN_FILENO
) < 0)
650 if (dup2(fd
, STDOUT_FILENO
) < 0)
657 *_saved_stdin
= saved_stdin
;
658 *_saved_stdout
= saved_stdout
;
660 saved_stdin
= saved_stdout
= -1;
665 _printf_(1, 2) static int write_confirm_message(const char *format
, ...) {
666 _cleanup_close_
int fd
= -1;
671 fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
675 va_start(ap
, format
);
676 vdprintf(fd
, format
, ap
);
682 static int restore_confirm_stdio(int *saved_stdin
, int *saved_stdout
) {
686 assert(saved_stdout
);
690 if (*saved_stdin
>= 0)
691 if (dup2(*saved_stdin
, STDIN_FILENO
) < 0)
694 if (*saved_stdout
>= 0)
695 if (dup2(*saved_stdout
, STDOUT_FILENO
) < 0)
698 *saved_stdin
= safe_close(*saved_stdin
);
699 *saved_stdout
= safe_close(*saved_stdout
);
704 static int ask_for_confirmation(char *response
, char **argv
) {
705 int saved_stdout
= -1, saved_stdin
= -1, r
;
706 _cleanup_free_
char *line
= NULL
;
708 r
= setup_confirm_stdio(&saved_stdin
, &saved_stdout
);
712 line
= exec_command_line(argv
);
716 r
= ask_char(response
, "yns", "Execute %s? [Yes, No, Skip] ", line
);
718 restore_confirm_stdio(&saved_stdin
, &saved_stdout
);
723 static int enforce_groups(const ExecContext
*context
, const char *username
, gid_t gid
) {
724 bool keep_groups
= false;
729 /* Lookup and set GID and supplementary group list. Here too
730 * we avoid NSS lookups for gid=0. */
732 if (context
->group
|| username
) {
733 /* First step, initialize groups from /etc/groups */
734 if (username
&& gid
!= 0) {
735 if (initgroups(username
, gid
) < 0)
741 /* Second step, set our gids */
742 if (setresgid(gid
, gid
, gid
) < 0)
746 if (context
->supplementary_groups
) {
751 /* Final step, initialize any manually set supplementary groups */
752 assert_se((ngroups_max
= (int) sysconf(_SC_NGROUPS_MAX
)) > 0);
754 if (!(gids
= new(gid_t
, ngroups_max
)))
758 k
= getgroups(ngroups_max
, gids
);
766 STRV_FOREACH(i
, context
->supplementary_groups
) {
769 if (k
>= ngroups_max
) {
775 r
= get_group_creds(&g
, gids
+k
);
784 r
= maybe_setgroups(k
, gids
);
796 static int enforce_user(const ExecContext
*context
, uid_t uid
) {
799 /* Sets (but doesn't look up) the uid and make sure we keep the
800 * capabilities while doing so. */
802 if (context
->capability_ambient_set
!= 0) {
804 /* First step: If we need to keep capabilities but
805 * drop privileges we need to make sure we keep our
806 * caps, while we drop privileges. */
808 int sb
= context
->secure_bits
| 1<<SECURE_KEEP_CAPS
;
810 if (prctl(PR_GET_SECUREBITS
) != sb
)
811 if (prctl(PR_SET_SECUREBITS
, sb
) < 0)
816 /* Second step: actually set the uids */
817 if (setresuid(uid
, uid
, uid
) < 0)
820 /* At this point we should have all necessary capabilities but
821 are otherwise a normal user. However, the caps might got
822 corrupted due to the setresuid() so we need clean them up
823 later. This is done outside of this call. */
830 static int null_conv(
832 const struct pam_message
**msg
,
833 struct pam_response
**resp
,
836 /* We don't support conversations */
843 static int setup_pam(
850 int fds
[], unsigned n_fds
) {
854 static const struct pam_conv conv
= {
859 _cleanup_(barrier_destroy
) Barrier barrier
= BARRIER_NULL
;
860 pam_handle_t
*handle
= NULL
;
862 int pam_code
= PAM_SUCCESS
, r
;
863 char **nv
, **e
= NULL
;
864 bool close_session
= false;
865 pid_t pam_pid
= 0, parent_pid
;
872 /* We set up PAM in the parent process, then fork. The child
873 * will then stay around until killed via PR_GET_PDEATHSIG or
874 * systemd via the cgroup logic. It will then remove the PAM
875 * session again. The parent process will exec() the actual
876 * daemon. We do things this way to ensure that the main PID
877 * of the daemon is the one we initially fork()ed. */
879 r
= barrier_create(&barrier
);
883 if (log_get_max_level() < LOG_DEBUG
)
886 pam_code
= pam_start(name
, user
, &conv
, &handle
);
887 if (pam_code
!= PAM_SUCCESS
) {
893 pam_code
= pam_set_item(handle
, PAM_TTY
, tty
);
894 if (pam_code
!= PAM_SUCCESS
)
898 STRV_FOREACH(nv
, *env
) {
899 pam_code
= pam_putenv(handle
, *nv
);
900 if (pam_code
!= PAM_SUCCESS
)
904 pam_code
= pam_acct_mgmt(handle
, flags
);
905 if (pam_code
!= PAM_SUCCESS
)
908 pam_code
= pam_open_session(handle
, flags
);
909 if (pam_code
!= PAM_SUCCESS
)
912 close_session
= true;
914 e
= pam_getenvlist(handle
);
916 pam_code
= PAM_BUF_ERR
;
920 /* Block SIGTERM, so that we know that it won't get lost in
923 assert_se(sigprocmask_many(SIG_BLOCK
, &old_ss
, SIGTERM
, -1) >= 0);
925 parent_pid
= getpid();
934 int sig
, ret
= EXIT_PAM
;
936 /* The child's job is to reset the PAM session on
938 barrier_set_role(&barrier
, BARRIER_CHILD
);
940 /* This string must fit in 10 chars (i.e. the length
941 * of "/sbin/init"), to look pretty in /bin/ps */
942 rename_process("(sd-pam)");
944 /* Make sure we don't keep open the passed fds in this
945 child. We assume that otherwise only those fds are
946 open here that have been opened by PAM. */
947 close_many(fds
, n_fds
);
949 /* Drop privileges - we don't need any to pam_close_session
950 * and this will make PR_SET_PDEATHSIG work in most cases.
951 * If this fails, ignore the error - but expect sd-pam threads
952 * to fail to exit normally */
954 r
= maybe_setgroups(0, NULL
);
956 log_warning_errno(r
, "Failed to setgroups() in sd-pam: %m");
957 if (setresgid(gid
, gid
, gid
) < 0)
958 log_warning_errno(errno
, "Failed to setresgid() in sd-pam: %m");
959 if (setresuid(uid
, uid
, uid
) < 0)
960 log_warning_errno(errno
, "Failed to setresuid() in sd-pam: %m");
962 (void) ignore_signals(SIGPIPE
, -1);
964 /* Wait until our parent died. This will only work if
965 * the above setresuid() succeeds, otherwise the kernel
966 * will not allow unprivileged parents kill their privileged
967 * children this way. We rely on the control groups kill logic
968 * to do the rest for us. */
969 if (prctl(PR_SET_PDEATHSIG
, SIGTERM
) < 0)
972 /* Tell the parent that our setup is done. This is especially
973 * important regarding dropping privileges. Otherwise, unit
974 * setup might race against our setresuid(2) call. */
975 barrier_place(&barrier
);
977 /* Check if our parent process might already have
979 if (getppid() == parent_pid
) {
982 assert_se(sigemptyset(&ss
) >= 0);
983 assert_se(sigaddset(&ss
, SIGTERM
) >= 0);
986 if (sigwait(&ss
, &sig
) < 0) {
993 assert(sig
== SIGTERM
);
998 /* If our parent died we'll end the session */
999 if (getppid() != parent_pid
) {
1000 pam_code
= pam_close_session(handle
, flags
);
1001 if (pam_code
!= PAM_SUCCESS
)
1008 pam_end(handle
, pam_code
| flags
);
1012 barrier_set_role(&barrier
, BARRIER_PARENT
);
1014 /* If the child was forked off successfully it will do all the
1015 * cleanups, so forget about the handle here. */
1018 /* Unblock SIGTERM again in the parent */
1019 assert_se(sigprocmask(SIG_SETMASK
, &old_ss
, NULL
) >= 0);
1021 /* We close the log explicitly here, since the PAM modules
1022 * might have opened it, but we don't want this fd around. */
1025 /* Synchronously wait for the child to initialize. We don't care for
1026 * errors as we cannot recover. However, warn loudly if it happens. */
1027 if (!barrier_place_and_sync(&barrier
))
1028 log_error("PAM initialization failed");
1036 if (pam_code
!= PAM_SUCCESS
) {
1037 log_error("PAM failed: %s", pam_strerror(handle
, pam_code
));
1038 r
= -EPERM
; /* PAM errors do not map to errno */
1040 log_error_errno(r
, "PAM failed: %m");
1044 pam_code
= pam_close_session(handle
, flags
);
1046 pam_end(handle
, pam_code
| flags
);
1058 static void rename_process_from_path(const char *path
) {
1059 char process_name
[11];
1063 /* This resulting string must fit in 10 chars (i.e. the length
1064 * of "/sbin/init") to look pretty in /bin/ps */
1068 rename_process("(...)");
1074 /* The end of the process name is usually more
1075 * interesting, since the first bit might just be
1081 process_name
[0] = '(';
1082 memcpy(process_name
+1, p
, l
);
1083 process_name
[1+l
] = ')';
1084 process_name
[1+l
+1] = 0;
1086 rename_process(process_name
);
1091 static bool skip_seccomp_unavailable(const Unit
* u
, const char* msg
) {
1092 if (!is_seccomp_available()) {
1094 log_unit_debug(u
, "SECCOMP features not detected in the kernel, skipping %s", msg
);
1101 static int apply_seccomp(const Unit
* u
, const ExecContext
*c
) {
1102 uint32_t negative_action
, action
;
1103 scmp_filter_ctx
*seccomp
;
1110 if (skip_seccomp_unavailable(u
, "syscall filtering"))
1113 negative_action
= c
->syscall_errno
== 0 ? SCMP_ACT_KILL
: SCMP_ACT_ERRNO(c
->syscall_errno
);
1115 seccomp
= seccomp_init(c
->syscall_whitelist
? negative_action
: SCMP_ACT_ALLOW
);
1119 if (c
->syscall_archs
) {
1121 SET_FOREACH(id
, c
->syscall_archs
, i
) {
1122 r
= seccomp_arch_add(seccomp
, PTR_TO_UINT32(id
) - 1);
1130 r
= seccomp_add_secondary_archs(seccomp
);
1135 action
= c
->syscall_whitelist
? SCMP_ACT_ALLOW
: negative_action
;
1136 SET_FOREACH(id
, c
->syscall_filter
, i
) {
1137 r
= seccomp_rule_add(seccomp
, action
, PTR_TO_INT(id
) - 1, 0);
1142 r
= seccomp_attr_set(seccomp
, SCMP_FLTATR_CTL_NNP
, 0);
1146 r
= seccomp_load(seccomp
);
1149 seccomp_release(seccomp
);
1153 static int apply_address_families(const Unit
* u
, const ExecContext
*c
) {
1154 scmp_filter_ctx
*seccomp
;
1160 if (skip_seccomp_unavailable(u
, "RestrictAddressFamilies="))
1163 seccomp
= seccomp_init(SCMP_ACT_ALLOW
);
1167 r
= seccomp_add_secondary_archs(seccomp
);
1171 if (c
->address_families_whitelist
) {
1172 int af
, first
= 0, last
= 0;
1175 /* If this is a whitelist, we first block the address
1176 * families that are out of range and then everything
1177 * that is not in the set. First, we find the lowest
1178 * and highest address family in the set. */
1180 SET_FOREACH(afp
, c
->address_families
, i
) {
1181 af
= PTR_TO_INT(afp
);
1183 if (af
<= 0 || af
>= af_max())
1186 if (first
== 0 || af
< first
)
1189 if (last
== 0 || af
> last
)
1193 assert((first
== 0) == (last
== 0));
1197 /* No entries in the valid range, block everything */
1198 r
= seccomp_rule_add(
1200 SCMP_ACT_ERRNO(EPROTONOSUPPORT
),
1208 /* Block everything below the first entry */
1209 r
= seccomp_rule_add(
1211 SCMP_ACT_ERRNO(EPROTONOSUPPORT
),
1214 SCMP_A0(SCMP_CMP_LT
, first
));
1218 /* Block everything above the last entry */
1219 r
= seccomp_rule_add(
1221 SCMP_ACT_ERRNO(EPROTONOSUPPORT
),
1224 SCMP_A0(SCMP_CMP_GT
, last
));
1228 /* Block everything between the first and last
1230 for (af
= 1; af
< af_max(); af
++) {
1232 if (set_contains(c
->address_families
, INT_TO_PTR(af
)))
1235 r
= seccomp_rule_add(
1237 SCMP_ACT_ERRNO(EPROTONOSUPPORT
),
1240 SCMP_A0(SCMP_CMP_EQ
, af
));
1249 /* If this is a blacklist, then generate one rule for
1250 * each address family that are then combined in OR
1253 SET_FOREACH(af
, c
->address_families
, i
) {
1255 r
= seccomp_rule_add(
1257 SCMP_ACT_ERRNO(EPROTONOSUPPORT
),
1260 SCMP_A0(SCMP_CMP_EQ
, PTR_TO_INT(af
)));
1266 r
= seccomp_attr_set(seccomp
, SCMP_FLTATR_CTL_NNP
, 0);
1270 r
= seccomp_load(seccomp
);
1273 seccomp_release(seccomp
);
1277 static int apply_memory_deny_write_execute(const Unit
* u
, const ExecContext
*c
) {
1278 scmp_filter_ctx
*seccomp
;
1283 if (skip_seccomp_unavailable(u
, "MemoryDenyWriteExecute="))
1286 seccomp
= seccomp_init(SCMP_ACT_ALLOW
);
1290 r
= seccomp_add_secondary_archs(seccomp
);
1294 r
= seccomp_rule_add(
1296 SCMP_ACT_ERRNO(EPERM
),
1299 SCMP_A2(SCMP_CMP_MASKED_EQ
, PROT_EXEC
|PROT_WRITE
, PROT_EXEC
|PROT_WRITE
));
1303 r
= seccomp_rule_add(
1305 SCMP_ACT_ERRNO(EPERM
),
1308 SCMP_A2(SCMP_CMP_MASKED_EQ
, PROT_EXEC
, PROT_EXEC
));
1312 r
= seccomp_attr_set(seccomp
, SCMP_FLTATR_CTL_NNP
, 0);
1316 r
= seccomp_load(seccomp
);
1319 seccomp_release(seccomp
);
1323 static int apply_restrict_realtime(const Unit
* u
, const ExecContext
*c
) {
1324 static const int permitted_policies
[] = {
1330 scmp_filter_ctx
*seccomp
;
1332 int r
, p
, max_policy
= 0;
1336 if (skip_seccomp_unavailable(u
, "RestrictRealtime="))
1339 seccomp
= seccomp_init(SCMP_ACT_ALLOW
);
1343 r
= seccomp_add_secondary_archs(seccomp
);
1347 /* Determine the highest policy constant we want to allow */
1348 for (i
= 0; i
< ELEMENTSOF(permitted_policies
); i
++)
1349 if (permitted_policies
[i
] > max_policy
)
1350 max_policy
= permitted_policies
[i
];
1352 /* Go through all policies with lower values than that, and block them -- unless they appear in the
1354 for (p
= 0; p
< max_policy
; p
++) {
1357 /* Check if this is in the whitelist. */
1358 for (i
= 0; i
< ELEMENTSOF(permitted_policies
); i
++)
1359 if (permitted_policies
[i
] == p
) {
1367 /* Deny this policy */
1368 r
= seccomp_rule_add(
1370 SCMP_ACT_ERRNO(EPERM
),
1371 SCMP_SYS(sched_setscheduler
),
1373 SCMP_A1(SCMP_CMP_EQ
, p
));
1378 /* Blacklist all other policies, i.e. the ones with higher values. Note that all comparisons are unsigned here,
1379 * hence no need no check for < 0 values. */
1380 r
= seccomp_rule_add(
1382 SCMP_ACT_ERRNO(EPERM
),
1383 SCMP_SYS(sched_setscheduler
),
1385 SCMP_A1(SCMP_CMP_GT
, max_policy
));
1389 r
= seccomp_attr_set(seccomp
, SCMP_FLTATR_CTL_NNP
, 0);
1393 r
= seccomp_load(seccomp
);
1396 seccomp_release(seccomp
);
1400 static int apply_protect_sysctl(Unit
*u
, const ExecContext
*c
) {
1401 scmp_filter_ctx
*seccomp
;
1406 /* Turn off the legacy sysctl() system call. Many distributions turn this off while building the kernel, but
1407 * let's protect even those systems where this is left on in the kernel. */
1409 if (skip_seccomp_unavailable(u
, "ProtectKernelTunables="))
1412 seccomp
= seccomp_init(SCMP_ACT_ALLOW
);
1416 r
= seccomp_add_secondary_archs(seccomp
);
1420 r
= seccomp_rule_add(
1422 SCMP_ACT_ERRNO(EPERM
),
1428 r
= seccomp_attr_set(seccomp
, SCMP_FLTATR_CTL_NNP
, 0);
1432 r
= seccomp_load(seccomp
);
1435 seccomp_release(seccomp
);
1439 static int apply_protect_kernel_modules(Unit
*u
, const ExecContext
*c
) {
1440 static const int module_syscalls
[] = {
1441 SCMP_SYS(delete_module
),
1442 SCMP_SYS(finit_module
),
1443 SCMP_SYS(init_module
),
1446 scmp_filter_ctx
*seccomp
;
1452 /* Turn of module syscalls on ProtectKernelModules=yes */
1454 if (skip_seccomp_unavailable(u
, "ProtectKernelModules="))
1457 seccomp
= seccomp_init(SCMP_ACT_ALLOW
);
1461 r
= seccomp_add_secondary_archs(seccomp
);
1465 for (i
= 0; i
< ELEMENTSOF(module_syscalls
); i
++) {
1466 r
= seccomp_rule_add(seccomp
, SCMP_ACT_ERRNO(EPERM
),
1467 module_syscalls
[i
], 0);
1472 r
= seccomp_attr_set(seccomp
, SCMP_FLTATR_CTL_NNP
, 0);
1476 r
= seccomp_load(seccomp
);
1479 seccomp_release(seccomp
);
1483 static int apply_private_devices(Unit
*u
, const ExecContext
*c
) {
1484 const SystemCallFilterSet
*set
;
1485 scmp_filter_ctx
*seccomp
;
1487 bool syscalls_found
= false;
1492 /* If PrivateDevices= is set, also turn off iopl and all @raw-io syscalls. */
1494 if (skip_seccomp_unavailable(u
, "PrivateDevices="))
1497 seccomp
= seccomp_init(SCMP_ACT_ALLOW
);
1501 r
= seccomp_add_secondary_archs(seccomp
);
1505 for (set
= syscall_filter_sets
; set
->set_name
; set
++)
1506 if (streq(set
->set_name
, "@raw-io")) {
1507 syscalls_found
= true;
1511 /* We should never fail here */
1512 if (!syscalls_found
) {
1517 NULSTR_FOREACH(sys
, set
->value
) {
1521 #ifndef __NR_s390_pci_mmio_read
1522 if (streq(sys
, "s390_pci_mmio_read"))
1525 #ifndef __NR_s390_pci_mmio_write
1526 if (streq(sys
, "s390_pci_mmio_write"))
1533 id
= seccomp_syscall_resolve_name(sys
);
1535 r
= seccomp_rule_add(
1537 SCMP_ACT_ERRNO(EPERM
),
1543 r
= seccomp_attr_set(seccomp
, SCMP_FLTATR_CTL_NNP
, 0);
1547 r
= seccomp_load(seccomp
);
1550 seccomp_release(seccomp
);
1556 static void do_idle_pipe_dance(int idle_pipe
[4]) {
1559 idle_pipe
[1] = safe_close(idle_pipe
[1]);
1560 idle_pipe
[2] = safe_close(idle_pipe
[2]);
1562 if (idle_pipe
[0] >= 0) {
1565 r
= fd_wait_for_event(idle_pipe
[0], POLLHUP
, IDLE_TIMEOUT_USEC
);
1567 if (idle_pipe
[3] >= 0 && r
== 0 /* timeout */) {
1570 /* Signal systemd that we are bored and want to continue. */
1571 n
= write(idle_pipe
[3], "x", 1);
1573 /* Wait for systemd to react to the signal above. */
1574 fd_wait_for_event(idle_pipe
[0], POLLHUP
, IDLE_TIMEOUT2_USEC
);
1577 idle_pipe
[0] = safe_close(idle_pipe
[0]);
1581 idle_pipe
[3] = safe_close(idle_pipe
[3]);
1584 static int build_environment(
1586 const ExecContext
*c
,
1587 const ExecParameters
*p
,
1590 const char *username
,
1592 dev_t journal_stream_dev
,
1593 ino_t journal_stream_ino
,
1596 _cleanup_strv_free_
char **our_env
= NULL
;
1604 our_env
= new0(char*, 14);
1609 _cleanup_free_
char *joined
= NULL
;
1611 if (asprintf(&x
, "LISTEN_PID="PID_FMT
, getpid()) < 0)
1613 our_env
[n_env
++] = x
;
1615 if (asprintf(&x
, "LISTEN_FDS=%u", n_fds
) < 0)
1617 our_env
[n_env
++] = x
;
1619 joined
= strv_join(p
->fd_names
, ":");
1623 x
= strjoin("LISTEN_FDNAMES=", joined
, NULL
);
1626 our_env
[n_env
++] = x
;
1629 if ((p
->flags
& EXEC_SET_WATCHDOG
) && p
->watchdog_usec
> 0) {
1630 if (asprintf(&x
, "WATCHDOG_PID="PID_FMT
, getpid()) < 0)
1632 our_env
[n_env
++] = x
;
1634 if (asprintf(&x
, "WATCHDOG_USEC="USEC_FMT
, p
->watchdog_usec
) < 0)
1636 our_env
[n_env
++] = x
;
1639 /* If this is D-Bus, tell the nss-systemd module, since it relies on being able to use D-Bus look up dynamic
1640 * users via PID 1, possibly dead-locking the dbus daemon. This way it will not use D-Bus to resolve names, but
1641 * check the database directly. */
1642 if (unit_has_name(u
, SPECIAL_DBUS_SERVICE
)) {
1643 x
= strdup("SYSTEMD_NSS_BYPASS_BUS=1");
1646 our_env
[n_env
++] = x
;
1650 x
= strappend("HOME=", home
);
1653 our_env
[n_env
++] = x
;
1657 x
= strappend("LOGNAME=", username
);
1660 our_env
[n_env
++] = x
;
1662 x
= strappend("USER=", username
);
1665 our_env
[n_env
++] = x
;
1669 x
= strappend("SHELL=", shell
);
1672 our_env
[n_env
++] = x
;
1675 if (!sd_id128_is_null(u
->invocation_id
)) {
1676 if (asprintf(&x
, "INVOCATION_ID=" SD_ID128_FORMAT_STR
, SD_ID128_FORMAT_VAL(u
->invocation_id
)) < 0)
1679 our_env
[n_env
++] = x
;
1682 if (exec_context_needs_term(c
)) {
1683 const char *tty_path
, *term
= NULL
;
1685 tty_path
= exec_context_tty_path(c
);
1687 /* If we are forked off PID 1 and we are supposed to operate on /dev/console, then let's try to inherit
1688 * the $TERM set for PID 1. This is useful for containers so that the $TERM the container manager
1689 * passes to PID 1 ends up all the way in the console login shown. */
1691 if (path_equal(tty_path
, "/dev/console") && getppid() == 1)
1692 term
= getenv("TERM");
1694 term
= default_term_for_tty(tty_path
);
1696 x
= strappend("TERM=", term
);
1699 our_env
[n_env
++] = x
;
1702 if (journal_stream_dev
!= 0 && journal_stream_ino
!= 0) {
1703 if (asprintf(&x
, "JOURNAL_STREAM=" DEV_FMT
":" INO_FMT
, journal_stream_dev
, journal_stream_ino
) < 0)
1706 our_env
[n_env
++] = x
;
1709 our_env
[n_env
++] = NULL
;
1710 assert(n_env
<= 12);
1718 static int build_pass_environment(const ExecContext
*c
, char ***ret
) {
1719 _cleanup_strv_free_
char **pass_env
= NULL
;
1720 size_t n_env
= 0, n_bufsize
= 0;
1723 STRV_FOREACH(i
, c
->pass_environment
) {
1724 _cleanup_free_
char *x
= NULL
;
1730 x
= strjoin(*i
, "=", v
, NULL
);
1733 if (!GREEDY_REALLOC(pass_env
, n_bufsize
, n_env
+ 2))
1735 pass_env
[n_env
++] = x
;
1736 pass_env
[n_env
] = NULL
;
1746 static bool exec_needs_mount_namespace(
1747 const ExecContext
*context
,
1748 const ExecParameters
*params
,
1749 ExecRuntime
*runtime
) {
1754 if (!strv_isempty(context
->read_write_paths
) ||
1755 !strv_isempty(context
->read_only_paths
) ||
1756 !strv_isempty(context
->inaccessible_paths
))
1759 if (context
->mount_flags
!= 0)
1762 if (context
->private_tmp
&& runtime
&& (runtime
->tmp_dir
|| runtime
->var_tmp_dir
))
1765 if (context
->private_devices
||
1766 context
->protect_system
!= PROTECT_SYSTEM_NO
||
1767 context
->protect_home
!= PROTECT_HOME_NO
||
1768 context
->protect_kernel_tunables
||
1769 context
->protect_kernel_modules
||
1770 context
->protect_control_groups
)
1776 static int setup_private_users(uid_t uid
, gid_t gid
) {
1777 _cleanup_free_
char *uid_map
= NULL
, *gid_map
= NULL
;
1778 _cleanup_close_pair_
int errno_pipe
[2] = { -1, -1 };
1779 _cleanup_close_
int unshare_ready_fd
= -1;
1780 _cleanup_(sigkill_waitp
) pid_t pid
= 0;
1786 /* Set up a user namespace and map root to root, the selected UID/GID to itself, and everything else to
1787 * nobody. In order to be able to write this mapping we need CAP_SETUID in the original user namespace, which
1788 * we however lack after opening the user namespace. To work around this we fork() a temporary child process,
1789 * which waits for the parent to create the new user namespace while staying in the original namespace. The
1790 * child then writes the UID mapping, under full privileges. The parent waits for the child to finish and
1791 * continues execution normally. */
1793 if (uid
!= 0 && uid_is_valid(uid
))
1795 "0 0 1\n" /* Map root → root */
1796 UID_FMT
" " UID_FMT
" 1\n", /* Map $UID → $UID */
1797 uid
, uid
); /* The case where the above is the same */
1799 uid_map
= strdup("0 0 1\n");
1803 if (gid
!= 0 && gid_is_valid(gid
))
1805 "0 0 1\n" /* Map root → root */
1806 GID_FMT
" " GID_FMT
" 1\n", /* Map $GID → $GID */
1809 gid_map
= strdup("0 0 1\n"); /* The case where the above is the same */
1813 /* Create a communication channel so that the parent can tell the child when it finished creating the user
1815 unshare_ready_fd
= eventfd(0, EFD_CLOEXEC
);
1816 if (unshare_ready_fd
< 0)
1819 /* Create a communication channel so that the child can tell the parent a proper error code in case it
1821 if (pipe2(errno_pipe
, O_CLOEXEC
) < 0)
1829 _cleanup_close_
int fd
= -1;
1833 /* Child process, running in the original user namespace. Let's update the parent's UID/GID map from
1834 * here, after the parent opened its own user namespace. */
1837 errno_pipe
[0] = safe_close(errno_pipe
[0]);
1839 /* Wait until the parent unshared the user namespace */
1840 if (read(unshare_ready_fd
, &c
, sizeof(c
)) < 0) {
1845 /* Disable the setgroups() system call in the child user namespace, for good. */
1846 a
= procfs_file_alloca(ppid
, "setgroups");
1847 fd
= open(a
, O_WRONLY
|O_CLOEXEC
);
1849 if (errno
!= ENOENT
) {
1854 /* If the file is missing the kernel is too old, let's continue anyway. */
1856 if (write(fd
, "deny\n", 5) < 0) {
1861 fd
= safe_close(fd
);
1864 /* First write the GID map */
1865 a
= procfs_file_alloca(ppid
, "gid_map");
1866 fd
= open(a
, O_WRONLY
|O_CLOEXEC
);
1871 if (write(fd
, gid_map
, strlen(gid_map
)) < 0) {
1875 fd
= safe_close(fd
);
1877 /* The write the UID map */
1878 a
= procfs_file_alloca(ppid
, "uid_map");
1879 fd
= open(a
, O_WRONLY
|O_CLOEXEC
);
1884 if (write(fd
, uid_map
, strlen(uid_map
)) < 0) {
1889 _exit(EXIT_SUCCESS
);
1892 (void) write(errno_pipe
[1], &r
, sizeof(r
));
1893 _exit(EXIT_FAILURE
);
1896 errno_pipe
[1] = safe_close(errno_pipe
[1]);
1898 if (unshare(CLONE_NEWUSER
) < 0)
1901 /* Let the child know that the namespace is ready now */
1902 if (write(unshare_ready_fd
, &c
, sizeof(c
)) < 0)
1905 /* Try to read an error code from the child */
1906 n
= read(errno_pipe
[0], &r
, sizeof(r
));
1909 if (n
== sizeof(r
)) { /* an error code was sent to us */
1914 if (n
!= 0) /* on success we should have read 0 bytes */
1917 r
= wait_for_terminate(pid
, &si
);
1922 /* If something strange happened with the child, let's consider this fatal, too */
1923 if (si
.si_code
!= CLD_EXITED
|| si
.si_status
!= 0)
1929 static int setup_runtime_directory(
1930 const ExecContext
*context
,
1931 const ExecParameters
*params
,
1941 STRV_FOREACH(rt
, context
->runtime_directory
) {
1942 _cleanup_free_
char *p
;
1944 p
= strjoin(params
->runtime_prefix
, "/", *rt
, NULL
);
1948 r
= mkdir_p_label(p
, context
->runtime_directory_mode
);
1952 r
= chmod_and_chown(p
, context
->runtime_directory_mode
, uid
, gid
);
1960 static int setup_smack(
1961 const ExecContext
*context
,
1962 const ExecCommand
*command
) {
1970 if (!mac_smack_use())
1973 if (context
->smack_process_label
) {
1974 r
= mac_smack_apply_pid(0, context
->smack_process_label
);
1978 #ifdef SMACK_DEFAULT_PROCESS_LABEL
1980 _cleanup_free_
char *exec_label
= NULL
;
1982 r
= mac_smack_read(command
->path
, SMACK_ATTR_EXEC
, &exec_label
);
1983 if (r
< 0 && r
!= -ENODATA
&& r
!= -EOPNOTSUPP
)
1986 r
= mac_smack_apply_pid(0, exec_label
? : SMACK_DEFAULT_PROCESS_LABEL
);
1996 static int compile_read_write_paths(
1997 const ExecContext
*context
,
1998 const ExecParameters
*params
,
2001 _cleanup_strv_free_
char **l
= NULL
;
2004 /* Compile the list of writable paths. This is the combination of the explicitly configured paths, plus all
2005 * runtime directories. */
2007 if (strv_isempty(context
->read_write_paths
) &&
2008 strv_isempty(context
->runtime_directory
)) {
2009 *ret
= NULL
; /* NOP if neither is set */
2013 l
= strv_copy(context
->read_write_paths
);
2017 STRV_FOREACH(rt
, context
->runtime_directory
) {
2020 s
= strjoin(params
->runtime_prefix
, "/", *rt
, NULL
);
2024 if (strv_consume(&l
, s
) < 0)
2034 static void append_socket_pair(int *array
, unsigned *n
, int pair
[2]) {
2042 array
[(*n
)++] = pair
[0];
2044 array
[(*n
)++] = pair
[1];
2047 static int close_remaining_fds(
2048 const ExecParameters
*params
,
2049 ExecRuntime
*runtime
,
2050 DynamicCreds
*dcreds
,
2053 int *fds
, unsigned n_fds
) {
2055 unsigned n_dont_close
= 0;
2056 int dont_close
[n_fds
+ 12];
2060 if (params
->stdin_fd
>= 0)
2061 dont_close
[n_dont_close
++] = params
->stdin_fd
;
2062 if (params
->stdout_fd
>= 0)
2063 dont_close
[n_dont_close
++] = params
->stdout_fd
;
2064 if (params
->stderr_fd
>= 0)
2065 dont_close
[n_dont_close
++] = params
->stderr_fd
;
2068 dont_close
[n_dont_close
++] = socket_fd
;
2070 memcpy(dont_close
+ n_dont_close
, fds
, sizeof(int) * n_fds
);
2071 n_dont_close
+= n_fds
;
2075 append_socket_pair(dont_close
, &n_dont_close
, runtime
->netns_storage_socket
);
2079 append_socket_pair(dont_close
, &n_dont_close
, dcreds
->user
->storage_socket
);
2081 append_socket_pair(dont_close
, &n_dont_close
, dcreds
->group
->storage_socket
);
2084 if (user_lookup_fd
>= 0)
2085 dont_close
[n_dont_close
++] = user_lookup_fd
;
2087 return close_all_fds(dont_close
, n_dont_close
);
2090 static bool context_has_address_families(const ExecContext
*c
) {
2093 return c
->address_families_whitelist
||
2094 !set_isempty(c
->address_families
);
2097 static bool context_has_syscall_filters(const ExecContext
*c
) {
2100 return c
->syscall_whitelist
||
2101 !set_isempty(c
->syscall_filter
) ||
2102 !set_isempty(c
->syscall_archs
);
2105 static bool context_has_no_new_privileges(const ExecContext
*c
) {
2108 if (c
->no_new_privileges
)
2111 if (have_effective_cap(CAP_SYS_ADMIN
)) /* if we are privileged, we don't need NNP */
2114 return context_has_address_families(c
) || /* we need NNP if we have any form of seccomp and are unprivileged */
2115 c
->memory_deny_write_execute
||
2116 c
->restrict_realtime
||
2117 c
->protect_kernel_tunables
||
2118 c
->protect_kernel_modules
||
2119 c
->private_devices
||
2120 context_has_syscall_filters(c
);
2123 static int send_user_lookup(
2131 /* Send the resolved UID/GID to PID 1 after we learnt it. We send a single datagram, containing the UID/GID
2132 * data as well as the unit name. Note that we suppress sending this if no user/group to resolve was
2135 if (user_lookup_fd
< 0)
2138 if (!uid_is_valid(uid
) && !gid_is_valid(gid
))
2141 if (writev(user_lookup_fd
,
2143 { .iov_base
= &uid
, .iov_len
= sizeof(uid
) },
2144 { .iov_base
= &gid
, .iov_len
= sizeof(gid
) },
2145 { .iov_base
= unit
->id
, .iov_len
= strlen(unit
->id
) }}, 3) < 0)
2151 static int exec_child(
2153 ExecCommand
*command
,
2154 const ExecContext
*context
,
2155 const ExecParameters
*params
,
2156 ExecRuntime
*runtime
,
2157 DynamicCreds
*dcreds
,
2160 int *fds
, unsigned n_fds
,
2165 _cleanup_strv_free_
char **our_env
= NULL
, **pass_env
= NULL
, **accum_env
= NULL
, **final_argv
= NULL
;
2166 _cleanup_free_
char *mac_selinux_context_net
= NULL
;
2167 const char *username
= NULL
, *home
= NULL
, *shell
= NULL
, *wd
;
2168 dev_t journal_stream_dev
= 0;
2169 ino_t journal_stream_ino
= 0;
2170 bool needs_mount_namespace
;
2171 uid_t uid
= UID_INVALID
;
2172 gid_t gid
= GID_INVALID
;
2179 assert(exit_status
);
2181 rename_process_from_path(command
->path
);
2183 /* We reset exactly these signals, since they are the
2184 * only ones we set to SIG_IGN in the main daemon. All
2185 * others we leave untouched because we set them to
2186 * SIG_DFL or a valid handler initially, both of which
2187 * will be demoted to SIG_DFL. */
2188 (void) default_signals(SIGNALS_CRASH_HANDLER
,
2189 SIGNALS_IGNORE
, -1);
2191 if (context
->ignore_sigpipe
)
2192 (void) ignore_signals(SIGPIPE
, -1);
2194 r
= reset_signal_mask();
2196 *exit_status
= EXIT_SIGNAL_MASK
;
2200 if (params
->idle_pipe
)
2201 do_idle_pipe_dance(params
->idle_pipe
);
2203 /* Close sockets very early to make sure we don't
2204 * block init reexecution because it cannot bind its
2209 r
= close_remaining_fds(params
, runtime
, dcreds
, user_lookup_fd
, socket_fd
, fds
, n_fds
);
2211 *exit_status
= EXIT_FDS
;
2215 if (!context
->same_pgrp
)
2217 *exit_status
= EXIT_SETSID
;
2221 exec_context_tty_reset(context
, params
);
2223 if (params
->flags
& EXEC_CONFIRM_SPAWN
) {
2226 r
= ask_for_confirmation(&response
, argv
);
2227 if (r
== -ETIMEDOUT
)
2228 write_confirm_message("Confirmation question timed out, assuming positive response.\n");
2230 write_confirm_message("Couldn't ask confirmation question, assuming positive response: %s\n", strerror(-r
));
2231 else if (response
== 's') {
2232 write_confirm_message("Skipping execution.\n");
2233 *exit_status
= EXIT_CONFIRM
;
2235 } else if (response
== 'n') {
2236 write_confirm_message("Failing execution.\n");
2242 if (context
->dynamic_user
&& dcreds
) {
2244 /* Make sure we bypass our own NSS module for any NSS checks */
2245 if (putenv((char*) "SYSTEMD_NSS_DYNAMIC_BYPASS=1") != 0) {
2246 *exit_status
= EXIT_USER
;
2250 r
= dynamic_creds_realize(dcreds
, &uid
, &gid
);
2252 *exit_status
= EXIT_USER
;
2256 if (!uid_is_valid(uid
) || !gid_is_valid(gid
)) {
2257 *exit_status
= EXIT_USER
;
2262 username
= dcreds
->user
->name
;
2265 if (context
->user
) {
2266 username
= context
->user
;
2267 r
= get_user_creds_clean(&username
, &uid
, &gid
, &home
, &shell
);
2269 *exit_status
= EXIT_USER
;
2273 /* Note that we don't set $HOME or $SHELL if they are not particularly enlightening anyway
2274 * (i.e. are "/" or "/bin/nologin"). */
2277 if (context
->group
) {
2278 const char *g
= context
->group
;
2280 r
= get_group_creds(&g
, &gid
);
2282 *exit_status
= EXIT_GROUP
;
2288 r
= send_user_lookup(unit
, user_lookup_fd
, uid
, gid
);
2290 *exit_status
= EXIT_USER
;
2294 user_lookup_fd
= safe_close(user_lookup_fd
);
2296 /* If a socket is connected to STDIN/STDOUT/STDERR, we
2297 * must sure to drop O_NONBLOCK */
2299 (void) fd_nonblock(socket_fd
, false);
2301 r
= setup_input(context
, params
, socket_fd
);
2303 *exit_status
= EXIT_STDIN
;
2307 r
= setup_output(unit
, context
, params
, STDOUT_FILENO
, socket_fd
, basename(command
->path
), uid
, gid
, &journal_stream_dev
, &journal_stream_ino
);
2309 *exit_status
= EXIT_STDOUT
;
2313 r
= setup_output(unit
, context
, params
, STDERR_FILENO
, socket_fd
, basename(command
->path
), uid
, gid
, &journal_stream_dev
, &journal_stream_ino
);
2315 *exit_status
= EXIT_STDERR
;
2319 if (params
->cgroup_path
) {
2320 r
= cg_attach_everywhere(params
->cgroup_supported
, params
->cgroup_path
, 0, NULL
, NULL
);
2322 *exit_status
= EXIT_CGROUP
;
2327 if (context
->oom_score_adjust_set
) {
2328 char t
[DECIMAL_STR_MAX(context
->oom_score_adjust
)];
2330 /* When we can't make this change due to EPERM, then
2331 * let's silently skip over it. User namespaces
2332 * prohibit write access to this file, and we
2333 * shouldn't trip up over that. */
2335 sprintf(t
, "%i", context
->oom_score_adjust
);
2336 r
= write_string_file("/proc/self/oom_score_adj", t
, 0);
2337 if (r
== -EPERM
|| r
== -EACCES
) {
2339 log_unit_debug_errno(unit
, r
, "Failed to adjust OOM setting, assuming containerized execution, ignoring: %m");
2342 *exit_status
= EXIT_OOM_ADJUST
;
2347 if (context
->nice_set
)
2348 if (setpriority(PRIO_PROCESS
, 0, context
->nice
) < 0) {
2349 *exit_status
= EXIT_NICE
;
2353 if (context
->cpu_sched_set
) {
2354 struct sched_param param
= {
2355 .sched_priority
= context
->cpu_sched_priority
,
2358 r
= sched_setscheduler(0,
2359 context
->cpu_sched_policy
|
2360 (context
->cpu_sched_reset_on_fork
?
2361 SCHED_RESET_ON_FORK
: 0),
2364 *exit_status
= EXIT_SETSCHEDULER
;
2369 if (context
->cpuset
)
2370 if (sched_setaffinity(0, CPU_ALLOC_SIZE(context
->cpuset_ncpus
), context
->cpuset
) < 0) {
2371 *exit_status
= EXIT_CPUAFFINITY
;
2375 if (context
->ioprio_set
)
2376 if (ioprio_set(IOPRIO_WHO_PROCESS
, 0, context
->ioprio
) < 0) {
2377 *exit_status
= EXIT_IOPRIO
;
2381 if (context
->timer_slack_nsec
!= NSEC_INFINITY
)
2382 if (prctl(PR_SET_TIMERSLACK
, context
->timer_slack_nsec
) < 0) {
2383 *exit_status
= EXIT_TIMERSLACK
;
2387 if (context
->personality
!= PERSONALITY_INVALID
)
2388 if (personality(context
->personality
) < 0) {
2389 *exit_status
= EXIT_PERSONALITY
;
2393 if (context
->utmp_id
)
2394 utmp_put_init_process(context
->utmp_id
, getpid(), getsid(0), context
->tty_path
,
2395 context
->utmp_mode
== EXEC_UTMP_INIT
? INIT_PROCESS
:
2396 context
->utmp_mode
== EXEC_UTMP_LOGIN
? LOGIN_PROCESS
:
2398 username
? "root" : context
->user
);
2400 if (context
->user
) {
2401 r
= chown_terminal(STDIN_FILENO
, uid
);
2403 *exit_status
= EXIT_STDIN
;
2408 /* If delegation is enabled we'll pass ownership of the cgroup
2409 * (but only in systemd's own controller hierarchy!) to the
2410 * user of the new process. */
2411 if (params
->cgroup_path
&& context
->user
&& params
->cgroup_delegate
) {
2412 r
= cg_set_task_access(SYSTEMD_CGROUP_CONTROLLER
, params
->cgroup_path
, 0644, uid
, gid
);
2414 *exit_status
= EXIT_CGROUP
;
2419 r
= cg_set_group_access(SYSTEMD_CGROUP_CONTROLLER
, params
->cgroup_path
, 0755, uid
, gid
);
2421 *exit_status
= EXIT_CGROUP
;
2426 if (!strv_isempty(context
->runtime_directory
) && params
->runtime_prefix
) {
2427 r
= setup_runtime_directory(context
, params
, uid
, gid
);
2429 *exit_status
= EXIT_RUNTIME_DIRECTORY
;
2434 r
= build_environment(
2446 *exit_status
= EXIT_MEMORY
;
2450 r
= build_pass_environment(context
, &pass_env
);
2452 *exit_status
= EXIT_MEMORY
;
2456 accum_env
= strv_env_merge(5,
2457 params
->environment
,
2460 context
->environment
,
2464 *exit_status
= EXIT_MEMORY
;
2467 accum_env
= strv_env_clean(accum_env
);
2469 (void) umask(context
->umask
);
2471 if ((params
->flags
& EXEC_APPLY_PERMISSIONS
) && !command
->privileged
) {
2472 r
= setup_smack(context
, command
);
2474 *exit_status
= EXIT_SMACK_PROCESS_LABEL
;
2478 if (context
->pam_name
&& username
) {
2479 r
= setup_pam(context
->pam_name
, username
, uid
, gid
, context
->tty_path
, &accum_env
, fds
, n_fds
);
2481 *exit_status
= EXIT_PAM
;
2487 if (context
->private_network
&& runtime
&& runtime
->netns_storage_socket
[0] >= 0) {
2488 r
= setup_netns(runtime
->netns_storage_socket
);
2490 *exit_status
= EXIT_NETWORK
;
2495 needs_mount_namespace
= exec_needs_mount_namespace(context
, params
, runtime
);
2496 if (needs_mount_namespace
) {
2497 _cleanup_free_
char **rw
= NULL
;
2498 char *tmp
= NULL
, *var
= NULL
;
2499 NameSpaceInfo ns_info
= {
2500 .private_dev
= context
->private_devices
,
2501 .protect_control_groups
= context
->protect_control_groups
,
2502 .protect_kernel_tunables
= context
->protect_kernel_tunables
,
2503 .protect_kernel_modules
= context
->protect_kernel_modules
,
2506 /* The runtime struct only contains the parent
2507 * of the private /tmp, which is
2508 * non-accessible to world users. Inside of it
2509 * there's a /tmp that is sticky, and that's
2510 * the one we want to use here. */
2512 if (context
->private_tmp
&& runtime
) {
2513 if (runtime
->tmp_dir
)
2514 tmp
= strjoina(runtime
->tmp_dir
, "/tmp");
2515 if (runtime
->var_tmp_dir
)
2516 var
= strjoina(runtime
->var_tmp_dir
, "/tmp");
2519 r
= compile_read_write_paths(context
, params
, &rw
);
2521 *exit_status
= EXIT_NAMESPACE
;
2525 r
= setup_namespace(
2526 (params
->flags
& EXEC_APPLY_CHROOT
) ? context
->root_directory
: NULL
,
2529 context
->read_only_paths
,
2530 context
->inaccessible_paths
,
2533 context
->protect_home
,
2534 context
->protect_system
,
2535 context
->mount_flags
);
2537 /* If we couldn't set up the namespace this is
2538 * probably due to a missing capability. In this case,
2539 * silently proceeed. */
2540 if (r
== -EPERM
|| r
== -EACCES
) {
2542 log_unit_debug_errno(unit
, r
, "Failed to set up namespace, assuming containerized execution, ignoring: %m");
2545 *exit_status
= EXIT_NAMESPACE
;
2550 if ((params
->flags
& EXEC_APPLY_PERMISSIONS
) && !command
->privileged
) {
2551 r
= enforce_groups(context
, username
, gid
);
2553 *exit_status
= EXIT_GROUP
;
2558 if (context
->working_directory_home
)
2560 else if (context
->working_directory
)
2561 wd
= context
->working_directory
;
2565 if (params
->flags
& EXEC_APPLY_CHROOT
) {
2566 if (!needs_mount_namespace
&& context
->root_directory
)
2567 if (chroot(context
->root_directory
) < 0) {
2568 *exit_status
= EXIT_CHROOT
;
2572 if (chdir(wd
) < 0 &&
2573 !context
->working_directory_missing_ok
) {
2574 *exit_status
= EXIT_CHDIR
;
2580 d
= strjoina(strempty(context
->root_directory
), "/", strempty(wd
));
2582 !context
->working_directory_missing_ok
) {
2583 *exit_status
= EXIT_CHDIR
;
2589 if ((params
->flags
& EXEC_APPLY_PERMISSIONS
) &&
2590 mac_selinux_use() &&
2591 params
->selinux_context_net
&&
2593 !command
->privileged
) {
2595 r
= mac_selinux_get_child_mls_label(socket_fd
, command
->path
, context
->selinux_context
, &mac_selinux_context_net
);
2597 *exit_status
= EXIT_SELINUX_CONTEXT
;
2603 if ((params
->flags
& EXEC_APPLY_PERMISSIONS
) && context
->private_users
) {
2604 r
= setup_private_users(uid
, gid
);
2606 *exit_status
= EXIT_USER
;
2611 /* We repeat the fd closing here, to make sure that
2612 * nothing is leaked from the PAM modules. Note that
2613 * we are more aggressive this time since socket_fd
2614 * and the netns fds we don't need anymore. The custom
2615 * endpoint fd was needed to upload the policy and can
2616 * now be closed as well. */
2617 r
= close_all_fds(fds
, n_fds
);
2619 r
= shift_fds(fds
, n_fds
);
2621 r
= flags_fds(fds
, n_fds
, context
->non_blocking
);
2623 *exit_status
= EXIT_FDS
;
2627 if ((params
->flags
& EXEC_APPLY_PERMISSIONS
) && !command
->privileged
) {
2629 int secure_bits
= context
->secure_bits
;
2631 for (i
= 0; i
< _RLIMIT_MAX
; i
++) {
2633 if (!context
->rlimit
[i
])
2636 r
= setrlimit_closest(i
, context
->rlimit
[i
]);
2638 *exit_status
= EXIT_LIMITS
;
2643 /* Set the RTPRIO resource limit to 0, but only if nothing else was explicitly requested. */
2644 if (context
->restrict_realtime
&& !context
->rlimit
[RLIMIT_RTPRIO
]) {
2645 if (setrlimit(RLIMIT_RTPRIO
, &RLIMIT_MAKE_CONST(0)) < 0) {
2646 *exit_status
= EXIT_LIMITS
;
2651 if (!cap_test_all(context
->capability_bounding_set
)) {
2652 r
= capability_bounding_set_drop(context
->capability_bounding_set
, false);
2654 *exit_status
= EXIT_CAPABILITIES
;
2659 /* This is done before enforce_user, but ambient set
2660 * does not survive over setresuid() if keep_caps is not set. */
2661 if (context
->capability_ambient_set
!= 0) {
2662 r
= capability_ambient_set_apply(context
->capability_ambient_set
, true);
2664 *exit_status
= EXIT_CAPABILITIES
;
2669 if (context
->user
) {
2670 r
= enforce_user(context
, uid
);
2672 *exit_status
= EXIT_USER
;
2675 if (context
->capability_ambient_set
!= 0) {
2677 /* Fix the ambient capabilities after user change. */
2678 r
= capability_ambient_set_apply(context
->capability_ambient_set
, false);
2680 *exit_status
= EXIT_CAPABILITIES
;
2684 /* If we were asked to change user and ambient capabilities
2685 * were requested, we had to add keep-caps to the securebits
2686 * so that we would maintain the inherited capability set
2687 * through the setresuid(). Make sure that the bit is added
2688 * also to the context secure_bits so that we don't try to
2689 * drop the bit away next. */
2691 secure_bits
|= 1<<SECURE_KEEP_CAPS
;
2695 /* PR_GET_SECUREBITS is not privileged, while
2696 * PR_SET_SECUREBITS is. So to suppress
2697 * potential EPERMs we'll try not to call
2698 * PR_SET_SECUREBITS unless necessary. */
2699 if (prctl(PR_GET_SECUREBITS
) != secure_bits
)
2700 if (prctl(PR_SET_SECUREBITS
, secure_bits
) < 0) {
2701 *exit_status
= EXIT_SECUREBITS
;
2705 if (context_has_no_new_privileges(context
))
2706 if (prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0) < 0) {
2707 *exit_status
= EXIT_NO_NEW_PRIVILEGES
;
2712 if (context_has_address_families(context
)) {
2713 r
= apply_address_families(unit
, context
);
2715 *exit_status
= EXIT_ADDRESS_FAMILIES
;
2720 if (context
->memory_deny_write_execute
) {
2721 r
= apply_memory_deny_write_execute(unit
, context
);
2723 *exit_status
= EXIT_SECCOMP
;
2728 if (context
->restrict_realtime
) {
2729 r
= apply_restrict_realtime(unit
, context
);
2731 *exit_status
= EXIT_SECCOMP
;
2736 if (context
->protect_kernel_tunables
) {
2737 r
= apply_protect_sysctl(unit
, context
);
2739 *exit_status
= EXIT_SECCOMP
;
2744 if (context
->protect_kernel_modules
) {
2745 r
= apply_protect_kernel_modules(unit
, context
);
2747 *exit_status
= EXIT_SECCOMP
;
2752 if (context
->private_devices
) {
2753 r
= apply_private_devices(unit
, context
);
2755 *exit_status
= EXIT_SECCOMP
;
2760 if (context_has_syscall_filters(context
)) {
2761 r
= apply_seccomp(unit
, context
);
2763 *exit_status
= EXIT_SECCOMP
;
2770 if (mac_selinux_use()) {
2771 char *exec_context
= mac_selinux_context_net
?: context
->selinux_context
;
2774 r
= setexeccon(exec_context
);
2776 *exit_status
= EXIT_SELINUX_CONTEXT
;
2783 #ifdef HAVE_APPARMOR
2784 if (context
->apparmor_profile
&& mac_apparmor_use()) {
2785 r
= aa_change_onexec(context
->apparmor_profile
);
2786 if (r
< 0 && !context
->apparmor_profile_ignore
) {
2787 *exit_status
= EXIT_APPARMOR_PROFILE
;
2794 final_argv
= replace_env_argv(argv
, accum_env
);
2796 *exit_status
= EXIT_MEMORY
;
2800 if (_unlikely_(log_get_max_level() >= LOG_DEBUG
)) {
2801 _cleanup_free_
char *line
;
2803 line
= exec_command_line(final_argv
);
2806 log_struct(LOG_DEBUG
,
2808 "EXECUTABLE=%s", command
->path
,
2809 LOG_UNIT_MESSAGE(unit
, "Executing: %s", line
),
2815 execve(command
->path
, final_argv
, accum_env
);
2816 *exit_status
= EXIT_EXEC
;
2820 int exec_spawn(Unit
*unit
,
2821 ExecCommand
*command
,
2822 const ExecContext
*context
,
2823 const ExecParameters
*params
,
2824 ExecRuntime
*runtime
,
2825 DynamicCreds
*dcreds
,
2828 _cleanup_strv_free_
char **files_env
= NULL
;
2829 int *fds
= NULL
; unsigned n_fds
= 0;
2830 _cleanup_free_
char *line
= NULL
;
2840 assert(params
->fds
|| params
->n_fds
<= 0);
2842 if (context
->std_input
== EXEC_INPUT_SOCKET
||
2843 context
->std_output
== EXEC_OUTPUT_SOCKET
||
2844 context
->std_error
== EXEC_OUTPUT_SOCKET
) {
2846 if (params
->n_fds
!= 1) {
2847 log_unit_error(unit
, "Got more than one socket.");
2851 socket_fd
= params
->fds
[0];
2855 n_fds
= params
->n_fds
;
2858 r
= exec_context_load_environment(unit
, context
, &files_env
);
2860 return log_unit_error_errno(unit
, r
, "Failed to load environment files: %m");
2862 argv
= params
->argv
?: command
->argv
;
2863 line
= exec_command_line(argv
);
2867 log_struct(LOG_DEBUG
,
2869 LOG_UNIT_MESSAGE(unit
, "About to execute: %s", line
),
2870 "EXECUTABLE=%s", command
->path
,
2874 return log_unit_error_errno(unit
, errno
, "Failed to fork: %m");
2879 r
= exec_child(unit
,
2889 unit
->manager
->user_lookup_fds
[1],
2893 log_struct_errno(LOG_ERR
, r
,
2894 LOG_MESSAGE_ID(SD_MESSAGE_SPAWN_FAILED
),
2896 LOG_UNIT_MESSAGE(unit
, "Failed at step %s spawning %s: %m",
2897 exit_status_to_string(exit_status
, EXIT_STATUS_SYSTEMD
),
2899 "EXECUTABLE=%s", command
->path
,
2906 log_unit_debug(unit
, "Forked %s as "PID_FMT
, command
->path
, pid
);
2908 /* We add the new process to the cgroup both in the child (so
2909 * that we can be sure that no user code is ever executed
2910 * outside of the cgroup) and in the parent (so that we can be
2911 * sure that when we kill the cgroup the process will be
2913 if (params
->cgroup_path
)
2914 (void) cg_attach(SYSTEMD_CGROUP_CONTROLLER
, params
->cgroup_path
, pid
);
2916 exec_status_start(&command
->exec_status
, pid
);
2922 void exec_context_init(ExecContext
*c
) {
2926 c
->ioprio
= IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE
, 0);
2927 c
->cpu_sched_policy
= SCHED_OTHER
;
2928 c
->syslog_priority
= LOG_DAEMON
|LOG_INFO
;
2929 c
->syslog_level_prefix
= true;
2930 c
->ignore_sigpipe
= true;
2931 c
->timer_slack_nsec
= NSEC_INFINITY
;
2932 c
->personality
= PERSONALITY_INVALID
;
2933 c
->runtime_directory_mode
= 0755;
2934 c
->capability_bounding_set
= CAP_ALL
;
2937 void exec_context_done(ExecContext
*c
) {
2942 c
->environment
= strv_free(c
->environment
);
2943 c
->environment_files
= strv_free(c
->environment_files
);
2944 c
->pass_environment
= strv_free(c
->pass_environment
);
2946 for (l
= 0; l
< ELEMENTSOF(c
->rlimit
); l
++)
2947 c
->rlimit
[l
] = mfree(c
->rlimit
[l
]);
2949 c
->working_directory
= mfree(c
->working_directory
);
2950 c
->root_directory
= mfree(c
->root_directory
);
2951 c
->tty_path
= mfree(c
->tty_path
);
2952 c
->syslog_identifier
= mfree(c
->syslog_identifier
);
2953 c
->user
= mfree(c
->user
);
2954 c
->group
= mfree(c
->group
);
2956 c
->supplementary_groups
= strv_free(c
->supplementary_groups
);
2958 c
->pam_name
= mfree(c
->pam_name
);
2960 c
->read_only_paths
= strv_free(c
->read_only_paths
);
2961 c
->read_write_paths
= strv_free(c
->read_write_paths
);
2962 c
->inaccessible_paths
= strv_free(c
->inaccessible_paths
);
2965 CPU_FREE(c
->cpuset
);
2967 c
->utmp_id
= mfree(c
->utmp_id
);
2968 c
->selinux_context
= mfree(c
->selinux_context
);
2969 c
->apparmor_profile
= mfree(c
->apparmor_profile
);
2971 c
->syscall_filter
= set_free(c
->syscall_filter
);
2972 c
->syscall_archs
= set_free(c
->syscall_archs
);
2973 c
->address_families
= set_free(c
->address_families
);
2975 c
->runtime_directory
= strv_free(c
->runtime_directory
);
2978 int exec_context_destroy_runtime_directory(ExecContext
*c
, const char *runtime_prefix
) {
2983 if (!runtime_prefix
)
2986 STRV_FOREACH(i
, c
->runtime_directory
) {
2987 _cleanup_free_
char *p
;
2989 p
= strjoin(runtime_prefix
, "/", *i
, NULL
);
2993 /* We execute this synchronously, since we need to be
2994 * sure this is gone when we start the service
2996 (void) rm_rf(p
, REMOVE_ROOT
);
3002 void exec_command_done(ExecCommand
*c
) {
3005 c
->path
= mfree(c
->path
);
3007 c
->argv
= strv_free(c
->argv
);
3010 void exec_command_done_array(ExecCommand
*c
, unsigned n
) {
3013 for (i
= 0; i
< n
; i
++)
3014 exec_command_done(c
+i
);
3017 ExecCommand
* exec_command_free_list(ExecCommand
*c
) {
3021 LIST_REMOVE(command
, c
, i
);
3022 exec_command_done(i
);
3029 void exec_command_free_array(ExecCommand
**c
, unsigned n
) {
3032 for (i
= 0; i
< n
; i
++)
3033 c
[i
] = exec_command_free_list(c
[i
]);
3036 typedef struct InvalidEnvInfo
{
3041 static void invalid_env(const char *p
, void *userdata
) {
3042 InvalidEnvInfo
*info
= userdata
;
3044 log_unit_error(info
->unit
, "Ignoring invalid environment assignment '%s': %s", p
, info
->path
);
3047 int exec_context_load_environment(Unit
*unit
, const ExecContext
*c
, char ***l
) {
3048 char **i
, **r
= NULL
;
3053 STRV_FOREACH(i
, c
->environment_files
) {
3056 bool ignore
= false;
3058 _cleanup_globfree_ glob_t pglob
= {};
3068 if (!path_is_absolute(fn
)) {
3076 /* Filename supports globbing, take all matching files */
3078 if (glob(fn
, 0, NULL
, &pglob
) != 0) {
3083 return errno
> 0 ? -errno
: -EINVAL
;
3085 count
= pglob
.gl_pathc
;
3093 for (n
= 0; n
< count
; n
++) {
3094 k
= load_env_file(NULL
, pglob
.gl_pathv
[n
], NULL
, &p
);
3102 /* Log invalid environment variables with filename */
3104 InvalidEnvInfo info
= {
3106 .path
= pglob
.gl_pathv
[n
]
3109 p
= strv_env_clean_with_callback(p
, invalid_env
, &info
);
3117 m
= strv_env_merge(2, r
, p
);
3133 static bool tty_may_match_dev_console(const char *tty
) {
3134 _cleanup_free_
char *active
= NULL
;
3140 if (startswith(tty
, "/dev/"))
3143 /* trivial identity? */
3144 if (streq(tty
, "console"))
3147 console
= resolve_dev_console(&active
);
3148 /* if we could not resolve, assume it may */
3152 /* "tty0" means the active VC, so it may be the same sometimes */
3153 return streq(console
, tty
) || (streq(console
, "tty0") && tty_is_vc(tty
));
3156 bool exec_context_may_touch_console(ExecContext
*ec
) {
3158 return (ec
->tty_reset
||
3160 ec
->tty_vt_disallocate
||
3161 is_terminal_input(ec
->std_input
) ||
3162 is_terminal_output(ec
->std_output
) ||
3163 is_terminal_output(ec
->std_error
)) &&
3164 tty_may_match_dev_console(exec_context_tty_path(ec
));
3167 static void strv_fprintf(FILE *f
, char **l
) {
3173 fprintf(f
, " %s", *g
);
3176 void exec_context_dump(ExecContext
*c
, FILE* f
, const char *prefix
) {
3183 prefix
= strempty(prefix
);
3187 "%sWorkingDirectory: %s\n"
3188 "%sRootDirectory: %s\n"
3189 "%sNonBlocking: %s\n"
3190 "%sPrivateTmp: %s\n"
3191 "%sPrivateDevices: %s\n"
3192 "%sProtectKernelTunables: %s\n"
3193 "%sProtectKernelModules: %s\n"
3194 "%sProtectControlGroups: %s\n"
3195 "%sPrivateNetwork: %s\n"
3196 "%sPrivateUsers: %s\n"
3197 "%sProtectHome: %s\n"
3198 "%sProtectSystem: %s\n"
3199 "%sIgnoreSIGPIPE: %s\n"
3200 "%sMemoryDenyWriteExecute: %s\n"
3201 "%sRestrictRealtime: %s\n",
3203 prefix
, c
->working_directory
? c
->working_directory
: "/",
3204 prefix
, c
->root_directory
? c
->root_directory
: "/",
3205 prefix
, yes_no(c
->non_blocking
),
3206 prefix
, yes_no(c
->private_tmp
),
3207 prefix
, yes_no(c
->private_devices
),
3208 prefix
, yes_no(c
->protect_kernel_tunables
),
3209 prefix
, yes_no(c
->protect_kernel_modules
),
3210 prefix
, yes_no(c
->protect_control_groups
),
3211 prefix
, yes_no(c
->private_network
),
3212 prefix
, yes_no(c
->private_users
),
3213 prefix
, protect_home_to_string(c
->protect_home
),
3214 prefix
, protect_system_to_string(c
->protect_system
),
3215 prefix
, yes_no(c
->ignore_sigpipe
),
3216 prefix
, yes_no(c
->memory_deny_write_execute
),
3217 prefix
, yes_no(c
->restrict_realtime
));
3219 STRV_FOREACH(e
, c
->environment
)
3220 fprintf(f
, "%sEnvironment: %s\n", prefix
, *e
);
3222 STRV_FOREACH(e
, c
->environment_files
)
3223 fprintf(f
, "%sEnvironmentFile: %s\n", prefix
, *e
);
3225 STRV_FOREACH(e
, c
->pass_environment
)
3226 fprintf(f
, "%sPassEnvironment: %s\n", prefix
, *e
);
3228 fprintf(f
, "%sRuntimeDirectoryMode: %04o\n", prefix
, c
->runtime_directory_mode
);
3230 STRV_FOREACH(d
, c
->runtime_directory
)
3231 fprintf(f
, "%sRuntimeDirectory: %s\n", prefix
, *d
);
3238 if (c
->oom_score_adjust_set
)
3240 "%sOOMScoreAdjust: %i\n",
3241 prefix
, c
->oom_score_adjust
);
3243 for (i
= 0; i
< RLIM_NLIMITS
; i
++)
3245 fprintf(f
, "%s%s: " RLIM_FMT
"\n",
3246 prefix
, rlimit_to_string(i
), c
->rlimit
[i
]->rlim_max
);
3247 fprintf(f
, "%s%sSoft: " RLIM_FMT
"\n",
3248 prefix
, rlimit_to_string(i
), c
->rlimit
[i
]->rlim_cur
);
3251 if (c
->ioprio_set
) {
3252 _cleanup_free_
char *class_str
= NULL
;
3254 ioprio_class_to_string_alloc(IOPRIO_PRIO_CLASS(c
->ioprio
), &class_str
);
3256 "%sIOSchedulingClass: %s\n"
3257 "%sIOPriority: %i\n",
3258 prefix
, strna(class_str
),
3259 prefix
, (int) IOPRIO_PRIO_DATA(c
->ioprio
));
3262 if (c
->cpu_sched_set
) {
3263 _cleanup_free_
char *policy_str
= NULL
;
3265 sched_policy_to_string_alloc(c
->cpu_sched_policy
, &policy_str
);
3267 "%sCPUSchedulingPolicy: %s\n"
3268 "%sCPUSchedulingPriority: %i\n"
3269 "%sCPUSchedulingResetOnFork: %s\n",
3270 prefix
, strna(policy_str
),
3271 prefix
, c
->cpu_sched_priority
,
3272 prefix
, yes_no(c
->cpu_sched_reset_on_fork
));
3276 fprintf(f
, "%sCPUAffinity:", prefix
);
3277 for (i
= 0; i
< c
->cpuset_ncpus
; i
++)
3278 if (CPU_ISSET_S(i
, CPU_ALLOC_SIZE(c
->cpuset_ncpus
), c
->cpuset
))
3279 fprintf(f
, " %u", i
);
3283 if (c
->timer_slack_nsec
!= NSEC_INFINITY
)
3284 fprintf(f
, "%sTimerSlackNSec: "NSEC_FMT
"\n", prefix
, c
->timer_slack_nsec
);
3287 "%sStandardInput: %s\n"
3288 "%sStandardOutput: %s\n"
3289 "%sStandardError: %s\n",
3290 prefix
, exec_input_to_string(c
->std_input
),
3291 prefix
, exec_output_to_string(c
->std_output
),
3292 prefix
, exec_output_to_string(c
->std_error
));
3298 "%sTTYVHangup: %s\n"
3299 "%sTTYVTDisallocate: %s\n",
3300 prefix
, c
->tty_path
,
3301 prefix
, yes_no(c
->tty_reset
),
3302 prefix
, yes_no(c
->tty_vhangup
),
3303 prefix
, yes_no(c
->tty_vt_disallocate
));
3305 if (c
->std_output
== EXEC_OUTPUT_SYSLOG
||
3306 c
->std_output
== EXEC_OUTPUT_KMSG
||
3307 c
->std_output
== EXEC_OUTPUT_JOURNAL
||
3308 c
->std_output
== EXEC_OUTPUT_SYSLOG_AND_CONSOLE
||
3309 c
->std_output
== EXEC_OUTPUT_KMSG_AND_CONSOLE
||
3310 c
->std_output
== EXEC_OUTPUT_JOURNAL_AND_CONSOLE
||
3311 c
->std_error
== EXEC_OUTPUT_SYSLOG
||
3312 c
->std_error
== EXEC_OUTPUT_KMSG
||
3313 c
->std_error
== EXEC_OUTPUT_JOURNAL
||
3314 c
->std_error
== EXEC_OUTPUT_SYSLOG_AND_CONSOLE
||
3315 c
->std_error
== EXEC_OUTPUT_KMSG_AND_CONSOLE
||
3316 c
->std_error
== EXEC_OUTPUT_JOURNAL_AND_CONSOLE
) {
3318 _cleanup_free_
char *fac_str
= NULL
, *lvl_str
= NULL
;
3320 log_facility_unshifted_to_string_alloc(c
->syslog_priority
>> 3, &fac_str
);
3321 log_level_to_string_alloc(LOG_PRI(c
->syslog_priority
), &lvl_str
);
3324 "%sSyslogFacility: %s\n"
3325 "%sSyslogLevel: %s\n",
3326 prefix
, strna(fac_str
),
3327 prefix
, strna(lvl_str
));
3331 fprintf(f
, "%sSecure Bits:%s%s%s%s%s%s\n",
3333 (c
->secure_bits
& 1<<SECURE_KEEP_CAPS
) ? " keep-caps" : "",
3334 (c
->secure_bits
& 1<<SECURE_KEEP_CAPS_LOCKED
) ? " keep-caps-locked" : "",
3335 (c
->secure_bits
& 1<<SECURE_NO_SETUID_FIXUP
) ? " no-setuid-fixup" : "",
3336 (c
->secure_bits
& 1<<SECURE_NO_SETUID_FIXUP_LOCKED
) ? " no-setuid-fixup-locked" : "",
3337 (c
->secure_bits
& 1<<SECURE_NOROOT
) ? " noroot" : "",
3338 (c
->secure_bits
& 1<<SECURE_NOROOT_LOCKED
) ? "noroot-locked" : "");
3340 if (c
->capability_bounding_set
!= CAP_ALL
) {
3342 fprintf(f
, "%sCapabilityBoundingSet:", prefix
);
3344 for (l
= 0; l
<= cap_last_cap(); l
++)
3345 if (c
->capability_bounding_set
& (UINT64_C(1) << l
))
3346 fprintf(f
, " %s", strna(capability_to_name(l
)));
3351 if (c
->capability_ambient_set
!= 0) {
3353 fprintf(f
, "%sAmbientCapabilities:", prefix
);
3355 for (l
= 0; l
<= cap_last_cap(); l
++)
3356 if (c
->capability_ambient_set
& (UINT64_C(1) << l
))
3357 fprintf(f
, " %s", strna(capability_to_name(l
)));
3363 fprintf(f
, "%sUser: %s\n", prefix
, c
->user
);
3365 fprintf(f
, "%sGroup: %s\n", prefix
, c
->group
);
3367 fprintf(f
, "%sDynamicUser: %s\n", prefix
, yes_no(c
->dynamic_user
));
3369 if (strv_length(c
->supplementary_groups
) > 0) {
3370 fprintf(f
, "%sSupplementaryGroups:", prefix
);
3371 strv_fprintf(f
, c
->supplementary_groups
);
3376 fprintf(f
, "%sPAMName: %s\n", prefix
, c
->pam_name
);
3378 if (strv_length(c
->read_write_paths
) > 0) {
3379 fprintf(f
, "%sReadWritePaths:", prefix
);
3380 strv_fprintf(f
, c
->read_write_paths
);
3384 if (strv_length(c
->read_only_paths
) > 0) {
3385 fprintf(f
, "%sReadOnlyPaths:", prefix
);
3386 strv_fprintf(f
, c
->read_only_paths
);
3390 if (strv_length(c
->inaccessible_paths
) > 0) {
3391 fprintf(f
, "%sInaccessiblePaths:", prefix
);
3392 strv_fprintf(f
, c
->inaccessible_paths
);
3398 "%sUtmpIdentifier: %s\n",
3399 prefix
, c
->utmp_id
);
3401 if (c
->selinux_context
)
3403 "%sSELinuxContext: %s%s\n",
3404 prefix
, c
->selinux_context_ignore
? "-" : "", c
->selinux_context
);
3406 if (c
->personality
!= PERSONALITY_INVALID
)
3408 "%sPersonality: %s\n",
3409 prefix
, strna(personality_to_string(c
->personality
)));
3411 if (c
->syscall_filter
) {
3419 "%sSystemCallFilter: ",
3422 if (!c
->syscall_whitelist
)
3426 SET_FOREACH(id
, c
->syscall_filter
, j
) {
3427 _cleanup_free_
char *name
= NULL
;
3434 name
= seccomp_syscall_resolve_num_arch(SCMP_ARCH_NATIVE
, PTR_TO_INT(id
) - 1);
3435 fputs(strna(name
), f
);
3442 if (c
->syscall_archs
) {
3449 "%sSystemCallArchitectures:",
3453 SET_FOREACH(id
, c
->syscall_archs
, j
)
3454 fprintf(f
, " %s", strna(seccomp_arch_to_string(PTR_TO_UINT32(id
) - 1)));
3459 if (c
->syscall_errno
> 0)
3461 "%sSystemCallErrorNumber: %s\n",
3462 prefix
, strna(errno_to_name(c
->syscall_errno
)));
3464 if (c
->apparmor_profile
)
3466 "%sAppArmorProfile: %s%s\n",
3467 prefix
, c
->apparmor_profile_ignore
? "-" : "", c
->apparmor_profile
);
3470 bool exec_context_maintains_privileges(ExecContext
*c
) {
3473 /* Returns true if the process forked off would run under
3474 * an unchanged UID or as root. */
3479 if (streq(c
->user
, "root") || streq(c
->user
, "0"))
3485 void exec_status_start(ExecStatus
*s
, pid_t pid
) {
3490 dual_timestamp_get(&s
->start_timestamp
);
3493 void exec_status_exit(ExecStatus
*s
, ExecContext
*context
, pid_t pid
, int code
, int status
) {
3496 if (s
->pid
&& s
->pid
!= pid
)
3500 dual_timestamp_get(&s
->exit_timestamp
);
3506 if (context
->utmp_id
)
3507 utmp_put_dead_process(context
->utmp_id
, pid
, code
, status
);
3509 exec_context_tty_reset(context
, NULL
);
3513 void exec_status_dump(ExecStatus
*s
, FILE *f
, const char *prefix
) {
3514 char buf
[FORMAT_TIMESTAMP_MAX
];
3522 prefix
= strempty(prefix
);
3525 "%sPID: "PID_FMT
"\n",
3528 if (dual_timestamp_is_set(&s
->start_timestamp
))
3530 "%sStart Timestamp: %s\n",
3531 prefix
, format_timestamp(buf
, sizeof(buf
), s
->start_timestamp
.realtime
));
3533 if (dual_timestamp_is_set(&s
->exit_timestamp
))
3535 "%sExit Timestamp: %s\n"
3537 "%sExit Status: %i\n",
3538 prefix
, format_timestamp(buf
, sizeof(buf
), s
->exit_timestamp
.realtime
),
3539 prefix
, sigchld_code_to_string(s
->code
),
3543 char *exec_command_line(char **argv
) {
3551 STRV_FOREACH(a
, argv
)
3554 if (!(n
= new(char, k
)))
3558 STRV_FOREACH(a
, argv
) {
3565 if (strpbrk(*a
, WHITESPACE
)) {
3576 /* FIXME: this doesn't really handle arguments that have
3577 * spaces and ticks in them */
3582 void exec_command_dump(ExecCommand
*c
, FILE *f
, const char *prefix
) {
3583 _cleanup_free_
char *cmd
= NULL
;
3584 const char *prefix2
;
3589 prefix
= strempty(prefix
);
3590 prefix2
= strjoina(prefix
, "\t");
3592 cmd
= exec_command_line(c
->argv
);
3594 "%sCommand Line: %s\n",
3595 prefix
, cmd
? cmd
: strerror(ENOMEM
));
3597 exec_status_dump(&c
->exec_status
, f
, prefix2
);
3600 void exec_command_dump_list(ExecCommand
*c
, FILE *f
, const char *prefix
) {
3603 prefix
= strempty(prefix
);
3605 LIST_FOREACH(command
, c
, c
)
3606 exec_command_dump(c
, f
, prefix
);
3609 void exec_command_append_list(ExecCommand
**l
, ExecCommand
*e
) {
3616 /* It's kind of important, that we keep the order here */
3617 LIST_FIND_TAIL(command
, *l
, end
);
3618 LIST_INSERT_AFTER(command
, *l
, end
, e
);
3623 int exec_command_set(ExecCommand
*c
, const char *path
, ...) {
3631 l
= strv_new_ap(path
, ap
);
3652 int exec_command_append(ExecCommand
*c
, const char *path
, ...) {
3653 _cleanup_strv_free_
char **l
= NULL
;
3661 l
= strv_new_ap(path
, ap
);
3667 r
= strv_extend_strv(&c
->argv
, l
, false);
3675 static int exec_runtime_allocate(ExecRuntime
**rt
) {
3680 *rt
= new0(ExecRuntime
, 1);
3685 (*rt
)->netns_storage_socket
[0] = (*rt
)->netns_storage_socket
[1] = -1;
3690 int exec_runtime_make(ExecRuntime
**rt
, ExecContext
*c
, const char *id
) {
3700 if (!c
->private_network
&& !c
->private_tmp
)
3703 r
= exec_runtime_allocate(rt
);
3707 if (c
->private_network
&& (*rt
)->netns_storage_socket
[0] < 0) {
3708 if (socketpair(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
, 0, (*rt
)->netns_storage_socket
) < 0)
3712 if (c
->private_tmp
&& !(*rt
)->tmp_dir
) {
3713 r
= setup_tmp_dirs(id
, &(*rt
)->tmp_dir
, &(*rt
)->var_tmp_dir
);
3721 ExecRuntime
*exec_runtime_ref(ExecRuntime
*r
) {
3723 assert(r
->n_ref
> 0);
3729 ExecRuntime
*exec_runtime_unref(ExecRuntime
*r
) {
3734 assert(r
->n_ref
> 0);
3741 free(r
->var_tmp_dir
);
3742 safe_close_pair(r
->netns_storage_socket
);
3746 int exec_runtime_serialize(Unit
*u
, ExecRuntime
*rt
, FILE *f
, FDSet
*fds
) {
3755 unit_serialize_item(u
, f
, "tmp-dir", rt
->tmp_dir
);
3757 if (rt
->var_tmp_dir
)
3758 unit_serialize_item(u
, f
, "var-tmp-dir", rt
->var_tmp_dir
);
3760 if (rt
->netns_storage_socket
[0] >= 0) {
3763 copy
= fdset_put_dup(fds
, rt
->netns_storage_socket
[0]);
3767 unit_serialize_item_format(u
, f
, "netns-socket-0", "%i", copy
);
3770 if (rt
->netns_storage_socket
[1] >= 0) {
3773 copy
= fdset_put_dup(fds
, rt
->netns_storage_socket
[1]);
3777 unit_serialize_item_format(u
, f
, "netns-socket-1", "%i", copy
);
3783 int exec_runtime_deserialize_item(Unit
*u
, ExecRuntime
**rt
, const char *key
, const char *value
, FDSet
*fds
) {
3790 if (streq(key
, "tmp-dir")) {
3793 r
= exec_runtime_allocate(rt
);
3797 copy
= strdup(value
);
3801 free((*rt
)->tmp_dir
);
3802 (*rt
)->tmp_dir
= copy
;
3804 } else if (streq(key
, "var-tmp-dir")) {
3807 r
= exec_runtime_allocate(rt
);
3811 copy
= strdup(value
);
3815 free((*rt
)->var_tmp_dir
);
3816 (*rt
)->var_tmp_dir
= copy
;
3818 } else if (streq(key
, "netns-socket-0")) {
3821 r
= exec_runtime_allocate(rt
);
3825 if (safe_atoi(value
, &fd
) < 0 || !fdset_contains(fds
, fd
))
3826 log_unit_debug(u
, "Failed to parse netns socket value: %s", value
);
3828 safe_close((*rt
)->netns_storage_socket
[0]);
3829 (*rt
)->netns_storage_socket
[0] = fdset_remove(fds
, fd
);
3831 } else if (streq(key
, "netns-socket-1")) {
3834 r
= exec_runtime_allocate(rt
);
3838 if (safe_atoi(value
, &fd
) < 0 || !fdset_contains(fds
, fd
))
3839 log_unit_debug(u
, "Failed to parse netns socket value: %s", value
);
3841 safe_close((*rt
)->netns_storage_socket
[1]);
3842 (*rt
)->netns_storage_socket
[1] = fdset_remove(fds
, fd
);
3850 static void *remove_tmpdir_thread(void *p
) {
3851 _cleanup_free_
char *path
= p
;
3853 (void) rm_rf(path
, REMOVE_ROOT
|REMOVE_PHYSICAL
);
3857 void exec_runtime_destroy(ExecRuntime
*rt
) {
3863 /* If there are multiple users of this, let's leave the stuff around */
3868 log_debug("Spawning thread to nuke %s", rt
->tmp_dir
);
3870 r
= asynchronous_job(remove_tmpdir_thread
, rt
->tmp_dir
);
3872 log_warning_errno(r
, "Failed to nuke %s: %m", rt
->tmp_dir
);
3879 if (rt
->var_tmp_dir
) {
3880 log_debug("Spawning thread to nuke %s", rt
->var_tmp_dir
);
3882 r
= asynchronous_job(remove_tmpdir_thread
, rt
->var_tmp_dir
);
3884 log_warning_errno(r
, "Failed to nuke %s: %m", rt
->var_tmp_dir
);
3885 free(rt
->var_tmp_dir
);
3888 rt
->var_tmp_dir
= NULL
;
3891 safe_close_pair(rt
->netns_storage_socket
);
3894 static const char* const exec_input_table
[_EXEC_INPUT_MAX
] = {
3895 [EXEC_INPUT_NULL
] = "null",
3896 [EXEC_INPUT_TTY
] = "tty",
3897 [EXEC_INPUT_TTY_FORCE
] = "tty-force",
3898 [EXEC_INPUT_TTY_FAIL
] = "tty-fail",
3899 [EXEC_INPUT_SOCKET
] = "socket"
3902 DEFINE_STRING_TABLE_LOOKUP(exec_input
, ExecInput
);
3904 static const char* const exec_output_table
[_EXEC_OUTPUT_MAX
] = {
3905 [EXEC_OUTPUT_INHERIT
] = "inherit",
3906 [EXEC_OUTPUT_NULL
] = "null",
3907 [EXEC_OUTPUT_TTY
] = "tty",
3908 [EXEC_OUTPUT_SYSLOG
] = "syslog",
3909 [EXEC_OUTPUT_SYSLOG_AND_CONSOLE
] = "syslog+console",
3910 [EXEC_OUTPUT_KMSG
] = "kmsg",
3911 [EXEC_OUTPUT_KMSG_AND_CONSOLE
] = "kmsg+console",
3912 [EXEC_OUTPUT_JOURNAL
] = "journal",
3913 [EXEC_OUTPUT_JOURNAL_AND_CONSOLE
] = "journal+console",
3914 [EXEC_OUTPUT_SOCKET
] = "socket"
3917 DEFINE_STRING_TABLE_LOOKUP(exec_output
, ExecOutput
);
3919 static const char* const exec_utmp_mode_table
[_EXEC_UTMP_MODE_MAX
] = {
3920 [EXEC_UTMP_INIT
] = "init",
3921 [EXEC_UTMP_LOGIN
] = "login",
3922 [EXEC_UTMP_USER
] = "user",
3925 DEFINE_STRING_TABLE_LOOKUP(exec_utmp_mode
, ExecUtmpMode
);