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>
29 #include <sys/personality.h>
30 #include <sys/prctl.h>
31 #include <sys/socket.h>
38 #include <security/pam_appl.h>
42 #include <selinux/selinux.h>
50 #include <sys/apparmor.h>
53 #include "sd-messages.h"
56 #include "alloc-util.h"
58 #include "apparmor-util.h"
63 #include "capability-util.h"
66 #include "errno-list.h"
68 #include "exit-status.h"
71 #include "formats-util.h"
73 #include "glob-util.h"
80 #include "namespace.h"
81 #include "parse-util.h"
82 #include "path-util.h"
83 #include "process-util.h"
84 #include "rlimit-util.h"
87 #include "seccomp-util.h"
89 #include "securebits.h"
90 #include "selinux-util.h"
91 #include "signal-util.h"
92 #include "smack-util.h"
93 #include "string-table.h"
94 #include "string-util.h"
96 #include "syslog-util.h"
97 #include "terminal-util.h"
99 #include "user-util.h"
101 #include "utmp-wtmp.h"
103 #define IDLE_TIMEOUT_USEC (5*USEC_PER_SEC)
104 #define IDLE_TIMEOUT2_USEC (1*USEC_PER_SEC)
106 /* This assumes there is a 'tty' group */
107 #define TTY_MODE 0620
109 #define SNDBUF_SIZE (8*1024*1024)
111 static int shift_fds(int fds
[], unsigned n_fds
) {
112 int start
, restart_from
;
117 /* Modifies the fds array! (sorts it) */
127 for (i
= start
; i
< (int) n_fds
; i
++) {
130 /* Already at right index? */
134 nfd
= fcntl(fds
[i
], F_DUPFD
, i
+ 3);
141 /* Hmm, the fd we wanted isn't free? Then
142 * let's remember that and try again from here */
143 if (nfd
!= i
+3 && restart_from
< 0)
147 if (restart_from
< 0)
150 start
= restart_from
;
156 static int flags_fds(const int fds
[], unsigned n_fds
, bool nonblock
) {
165 /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags */
167 for (i
= 0; i
< n_fds
; i
++) {
169 r
= fd_nonblock(fds
[i
], nonblock
);
173 /* We unconditionally drop FD_CLOEXEC from the fds,
174 * since after all we want to pass these fds to our
177 r
= fd_cloexec(fds
[i
], false);
185 static const char *exec_context_tty_path(const ExecContext
*context
) {
188 if (context
->stdio_as_fds
)
191 if (context
->tty_path
)
192 return context
->tty_path
;
194 return "/dev/console";
197 static void exec_context_tty_reset(const ExecContext
*context
, const ExecParameters
*p
) {
202 path
= exec_context_tty_path(context
);
204 if (context
->tty_vhangup
) {
205 if (p
&& p
->stdin_fd
>= 0)
206 (void) terminal_vhangup_fd(p
->stdin_fd
);
208 (void) terminal_vhangup(path
);
211 if (context
->tty_reset
) {
212 if (p
&& p
->stdin_fd
>= 0)
213 (void) reset_terminal_fd(p
->stdin_fd
, true);
215 (void) reset_terminal(path
);
218 if (context
->tty_vt_disallocate
&& path
)
219 (void) vt_disallocate(path
);
222 static bool is_terminal_output(ExecOutput o
) {
224 o
== EXEC_OUTPUT_TTY
||
225 o
== EXEC_OUTPUT_SYSLOG_AND_CONSOLE
||
226 o
== EXEC_OUTPUT_KMSG_AND_CONSOLE
||
227 o
== EXEC_OUTPUT_JOURNAL_AND_CONSOLE
;
230 static int open_null_as(int flags
, int nfd
) {
235 fd
= open("/dev/null", flags
|O_NOCTTY
);
240 r
= dup2(fd
, nfd
) < 0 ? -errno
: nfd
;
248 static int connect_journal_socket(int fd
, uid_t uid
, gid_t gid
) {
249 union sockaddr_union sa
= {
250 .un
.sun_family
= AF_UNIX
,
251 .un
.sun_path
= "/run/systemd/journal/stdout",
253 uid_t olduid
= UID_INVALID
;
254 gid_t oldgid
= GID_INVALID
;
257 if (gid
!= GID_INVALID
) {
265 if (uid
!= UID_INVALID
) {
275 r
= connect(fd
, &sa
.sa
, SOCKADDR_UN_LEN(sa
.un
));
279 /* If we fail to restore the uid or gid, things will likely
280 fail later on. This should only happen if an LSM interferes. */
282 if (uid
!= UID_INVALID
)
283 (void) seteuid(olduid
);
286 if (gid
!= GID_INVALID
)
287 (void) setegid(oldgid
);
292 static int connect_logger_as(
294 const ExecContext
*context
,
304 assert(output
< _EXEC_OUTPUT_MAX
);
308 fd
= socket(AF_UNIX
, SOCK_STREAM
, 0);
312 r
= connect_journal_socket(fd
, uid
, gid
);
316 if (shutdown(fd
, SHUT_RD
) < 0) {
321 (void) fd_inc_sndbuf(fd
, SNDBUF_SIZE
);
331 context
->syslog_identifier
? context
->syslog_identifier
: ident
,
333 context
->syslog_priority
,
334 !!context
->syslog_level_prefix
,
335 output
== EXEC_OUTPUT_SYSLOG
|| output
== EXEC_OUTPUT_SYSLOG_AND_CONSOLE
,
336 output
== EXEC_OUTPUT_KMSG
|| output
== EXEC_OUTPUT_KMSG_AND_CONSOLE
,
337 is_terminal_output(output
));
342 r
= dup2(fd
, nfd
) < 0 ? -errno
: nfd
;
347 static int open_terminal_as(const char *path
, mode_t mode
, int nfd
) {
353 fd
= open_terminal(path
, mode
| O_NOCTTY
);
358 r
= dup2(fd
, nfd
) < 0 ? -errno
: nfd
;
366 static bool is_terminal_input(ExecInput i
) {
368 i
== EXEC_INPUT_TTY
||
369 i
== EXEC_INPUT_TTY_FORCE
||
370 i
== EXEC_INPUT_TTY_FAIL
;
373 static int fixup_input(ExecInput std_input
, int socket_fd
, bool apply_tty_stdin
) {
375 if (is_terminal_input(std_input
) && !apply_tty_stdin
)
376 return EXEC_INPUT_NULL
;
378 if (std_input
== EXEC_INPUT_SOCKET
&& socket_fd
< 0)
379 return EXEC_INPUT_NULL
;
384 static int fixup_output(ExecOutput std_output
, int socket_fd
) {
386 if (std_output
== EXEC_OUTPUT_SOCKET
&& socket_fd
< 0)
387 return EXEC_OUTPUT_INHERIT
;
392 static int setup_input(
393 const ExecContext
*context
,
394 const ExecParameters
*params
,
402 if (params
->stdin_fd
>= 0) {
403 if (dup2(params
->stdin_fd
, STDIN_FILENO
) < 0)
406 /* Try to make this the controlling tty, if it is a tty, and reset it */
407 (void) ioctl(STDIN_FILENO
, TIOCSCTTY
, context
->std_input
== EXEC_INPUT_TTY_FORCE
);
408 (void) reset_terminal_fd(STDIN_FILENO
, true);
413 i
= fixup_input(context
->std_input
, socket_fd
, params
->apply_tty_stdin
);
417 case EXEC_INPUT_NULL
:
418 return open_null_as(O_RDONLY
, STDIN_FILENO
);
421 case EXEC_INPUT_TTY_FORCE
:
422 case EXEC_INPUT_TTY_FAIL
: {
425 fd
= acquire_terminal(exec_context_tty_path(context
),
426 i
== EXEC_INPUT_TTY_FAIL
,
427 i
== EXEC_INPUT_TTY_FORCE
,
433 if (fd
!= STDIN_FILENO
) {
434 r
= dup2(fd
, STDIN_FILENO
) < 0 ? -errno
: STDIN_FILENO
;
442 case EXEC_INPUT_SOCKET
:
443 return dup2(socket_fd
, STDIN_FILENO
) < 0 ? -errno
: STDIN_FILENO
;
446 assert_not_reached("Unknown input type");
450 static int setup_output(
452 const ExecContext
*context
,
453 const ExecParameters
*params
,
459 dev_t
*journal_stream_dev
,
460 ino_t
*journal_stream_ino
) {
470 assert(journal_stream_dev
);
471 assert(journal_stream_ino
);
473 if (fileno
== STDOUT_FILENO
&& params
->stdout_fd
>= 0) {
475 if (dup2(params
->stdout_fd
, STDOUT_FILENO
) < 0)
478 return STDOUT_FILENO
;
481 if (fileno
== STDERR_FILENO
&& params
->stderr_fd
>= 0) {
482 if (dup2(params
->stderr_fd
, STDERR_FILENO
) < 0)
485 return STDERR_FILENO
;
488 i
= fixup_input(context
->std_input
, socket_fd
, params
->apply_tty_stdin
);
489 o
= fixup_output(context
->std_output
, socket_fd
);
491 if (fileno
== STDERR_FILENO
) {
493 e
= fixup_output(context
->std_error
, socket_fd
);
495 /* This expects the input and output are already set up */
497 /* Don't change the stderr file descriptor if we inherit all
498 * the way and are not on a tty */
499 if (e
== EXEC_OUTPUT_INHERIT
&&
500 o
== EXEC_OUTPUT_INHERIT
&&
501 i
== EXEC_INPUT_NULL
&&
502 !is_terminal_input(context
->std_input
) &&
506 /* Duplicate from stdout if possible */
507 if (e
== o
|| e
== EXEC_OUTPUT_INHERIT
)
508 return dup2(STDOUT_FILENO
, fileno
) < 0 ? -errno
: fileno
;
512 } else if (o
== EXEC_OUTPUT_INHERIT
) {
513 /* If input got downgraded, inherit the original value */
514 if (i
== EXEC_INPUT_NULL
&& is_terminal_input(context
->std_input
))
515 return open_terminal_as(exec_context_tty_path(context
), O_WRONLY
, fileno
);
517 /* If the input is connected to anything that's not a /dev/null, inherit that... */
518 if (i
!= EXEC_INPUT_NULL
)
519 return dup2(STDIN_FILENO
, fileno
) < 0 ? -errno
: fileno
;
521 /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */
525 /* We need to open /dev/null here anew, to get the right access mode. */
526 return open_null_as(O_WRONLY
, fileno
);
531 case EXEC_OUTPUT_NULL
:
532 return open_null_as(O_WRONLY
, fileno
);
534 case EXEC_OUTPUT_TTY
:
535 if (is_terminal_input(i
))
536 return dup2(STDIN_FILENO
, fileno
) < 0 ? -errno
: fileno
;
538 /* We don't reset the terminal if this is just about output */
539 return open_terminal_as(exec_context_tty_path(context
), O_WRONLY
, fileno
);
541 case EXEC_OUTPUT_SYSLOG
:
542 case EXEC_OUTPUT_SYSLOG_AND_CONSOLE
:
543 case EXEC_OUTPUT_KMSG
:
544 case EXEC_OUTPUT_KMSG_AND_CONSOLE
:
545 case EXEC_OUTPUT_JOURNAL
:
546 case EXEC_OUTPUT_JOURNAL_AND_CONSOLE
:
547 r
= connect_logger_as(unit
, context
, o
, ident
, fileno
, uid
, gid
);
549 log_unit_error_errno(unit
, r
, "Failed to connect %s to the journal socket, ignoring: %m", fileno
== STDOUT_FILENO
? "stdout" : "stderr");
550 r
= open_null_as(O_WRONLY
, fileno
);
554 /* If we connected this fd to the journal via a stream, patch the device/inode into the passed
555 * parameters, but only then. This is useful so that we can set $JOURNAL_STREAM that permits
556 * services to detect whether they are connected to the journal or not. */
558 if (fstat(fileno
, &st
) >= 0) {
559 *journal_stream_dev
= st
.st_dev
;
560 *journal_stream_ino
= st
.st_ino
;
565 case EXEC_OUTPUT_SOCKET
:
566 assert(socket_fd
>= 0);
567 return dup2(socket_fd
, fileno
) < 0 ? -errno
: fileno
;
570 assert_not_reached("Unknown error type");
574 static int chown_terminal(int fd
, uid_t uid
) {
579 /* Before we chown/chmod the TTY, let's ensure this is actually a tty */
583 /* This might fail. What matters are the results. */
584 (void) fchown(fd
, uid
, -1);
585 (void) fchmod(fd
, TTY_MODE
);
587 if (fstat(fd
, &st
) < 0)
590 if (st
.st_uid
!= uid
|| (st
.st_mode
& 0777) != TTY_MODE
)
596 static int setup_confirm_stdio(int *_saved_stdin
, int *_saved_stdout
) {
597 _cleanup_close_
int fd
= -1, saved_stdin
= -1, saved_stdout
= -1;
600 assert(_saved_stdin
);
601 assert(_saved_stdout
);
603 saved_stdin
= fcntl(STDIN_FILENO
, F_DUPFD
, 3);
607 saved_stdout
= fcntl(STDOUT_FILENO
, F_DUPFD
, 3);
608 if (saved_stdout
< 0)
611 fd
= acquire_terminal(
616 DEFAULT_CONFIRM_USEC
);
620 r
= chown_terminal(fd
, getuid());
624 r
= reset_terminal_fd(fd
, true);
628 if (dup2(fd
, STDIN_FILENO
) < 0)
631 if (dup2(fd
, STDOUT_FILENO
) < 0)
638 *_saved_stdin
= saved_stdin
;
639 *_saved_stdout
= saved_stdout
;
641 saved_stdin
= saved_stdout
= -1;
646 _printf_(1, 2) static int write_confirm_message(const char *format
, ...) {
647 _cleanup_close_
int fd
= -1;
652 fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
656 va_start(ap
, format
);
657 vdprintf(fd
, format
, ap
);
663 static int restore_confirm_stdio(int *saved_stdin
, int *saved_stdout
) {
667 assert(saved_stdout
);
671 if (*saved_stdin
>= 0)
672 if (dup2(*saved_stdin
, STDIN_FILENO
) < 0)
675 if (*saved_stdout
>= 0)
676 if (dup2(*saved_stdout
, STDOUT_FILENO
) < 0)
679 *saved_stdin
= safe_close(*saved_stdin
);
680 *saved_stdout
= safe_close(*saved_stdout
);
685 static int ask_for_confirmation(char *response
, char **argv
) {
686 int saved_stdout
= -1, saved_stdin
= -1, r
;
687 _cleanup_free_
char *line
= NULL
;
689 r
= setup_confirm_stdio(&saved_stdin
, &saved_stdout
);
693 line
= exec_command_line(argv
);
697 r
= ask_char(response
, "yns", "Execute %s? [Yes, No, Skip] ", line
);
699 restore_confirm_stdio(&saved_stdin
, &saved_stdout
);
704 static int enforce_groups(const ExecContext
*context
, const char *username
, gid_t gid
) {
705 bool keep_groups
= false;
710 /* Lookup and set GID and supplementary group list. Here too
711 * we avoid NSS lookups for gid=0. */
713 if (context
->group
|| username
) {
714 /* First step, initialize groups from /etc/groups */
715 if (username
&& gid
!= 0) {
716 if (initgroups(username
, gid
) < 0)
722 /* Second step, set our gids */
723 if (setresgid(gid
, gid
, gid
) < 0)
727 if (context
->supplementary_groups
) {
732 /* Final step, initialize any manually set supplementary groups */
733 assert_se((ngroups_max
= (int) sysconf(_SC_NGROUPS_MAX
)) > 0);
735 if (!(gids
= new(gid_t
, ngroups_max
)))
739 k
= getgroups(ngroups_max
, gids
);
747 STRV_FOREACH(i
, context
->supplementary_groups
) {
750 if (k
>= ngroups_max
) {
756 r
= get_group_creds(&g
, gids
+k
);
765 if (setgroups(k
, gids
) < 0) {
776 static int enforce_user(const ExecContext
*context
, uid_t uid
) {
779 /* Sets (but doesn't look up) the uid and make sure we keep the
780 * capabilities while doing so. */
782 if (context
->capability_ambient_set
!= 0) {
784 /* First step: If we need to keep capabilities but
785 * drop privileges we need to make sure we keep our
786 * caps, while we drop privileges. */
788 int sb
= context
->secure_bits
| 1<<SECURE_KEEP_CAPS
;
790 if (prctl(PR_GET_SECUREBITS
) != sb
)
791 if (prctl(PR_SET_SECUREBITS
, sb
) < 0)
796 /* Second step: actually set the uids */
797 if (setresuid(uid
, uid
, uid
) < 0)
800 /* At this point we should have all necessary capabilities but
801 are otherwise a normal user. However, the caps might got
802 corrupted due to the setresuid() so we need clean them up
803 later. This is done outside of this call. */
810 static int null_conv(
812 const struct pam_message
**msg
,
813 struct pam_response
**resp
,
816 /* We don't support conversations */
821 static int setup_pam(
827 int fds
[], unsigned n_fds
) {
829 static const struct pam_conv conv
= {
834 _cleanup_(barrier_destroy
) Barrier barrier
= BARRIER_NULL
;
835 pam_handle_t
*handle
= NULL
;
837 int pam_code
= PAM_SUCCESS
, r
;
838 char **nv
, **e
= NULL
;
839 bool close_session
= false;
840 pid_t pam_pid
= 0, parent_pid
;
847 /* We set up PAM in the parent process, then fork. The child
848 * will then stay around until killed via PR_GET_PDEATHSIG or
849 * systemd via the cgroup logic. It will then remove the PAM
850 * session again. The parent process will exec() the actual
851 * daemon. We do things this way to ensure that the main PID
852 * of the daemon is the one we initially fork()ed. */
854 r
= barrier_create(&barrier
);
858 if (log_get_max_level() < LOG_DEBUG
)
861 pam_code
= pam_start(name
, user
, &conv
, &handle
);
862 if (pam_code
!= PAM_SUCCESS
) {
868 pam_code
= pam_set_item(handle
, PAM_TTY
, tty
);
869 if (pam_code
!= PAM_SUCCESS
)
873 STRV_FOREACH(nv
, *env
) {
874 pam_code
= pam_putenv(handle
, *nv
);
875 if (pam_code
!= PAM_SUCCESS
)
879 pam_code
= pam_acct_mgmt(handle
, flags
);
880 if (pam_code
!= PAM_SUCCESS
)
883 pam_code
= pam_open_session(handle
, flags
);
884 if (pam_code
!= PAM_SUCCESS
)
887 close_session
= true;
889 e
= pam_getenvlist(handle
);
891 pam_code
= PAM_BUF_ERR
;
895 /* Block SIGTERM, so that we know that it won't get lost in
898 assert_se(sigprocmask_many(SIG_BLOCK
, &old_ss
, SIGTERM
, -1) >= 0);
900 parent_pid
= getpid();
909 int sig
, ret
= EXIT_PAM
;
911 /* The child's job is to reset the PAM session on
913 barrier_set_role(&barrier
, BARRIER_CHILD
);
915 /* This string must fit in 10 chars (i.e. the length
916 * of "/sbin/init"), to look pretty in /bin/ps */
917 rename_process("(sd-pam)");
919 /* Make sure we don't keep open the passed fds in this
920 child. We assume that otherwise only those fds are
921 open here that have been opened by PAM. */
922 close_many(fds
, n_fds
);
924 /* Drop privileges - we don't need any to pam_close_session
925 * and this will make PR_SET_PDEATHSIG work in most cases.
926 * If this fails, ignore the error - but expect sd-pam threads
927 * to fail to exit normally */
928 if (setresuid(uid
, uid
, uid
) < 0)
929 log_error_errno(r
, "Error: Failed to setresuid() in sd-pam: %m");
931 (void) ignore_signals(SIGPIPE
, -1);
933 /* Wait until our parent died. This will only work if
934 * the above setresuid() succeeds, otherwise the kernel
935 * will not allow unprivileged parents kill their privileged
936 * children this way. We rely on the control groups kill logic
937 * to do the rest for us. */
938 if (prctl(PR_SET_PDEATHSIG
, SIGTERM
) < 0)
941 /* Tell the parent that our setup is done. This is especially
942 * important regarding dropping privileges. Otherwise, unit
943 * setup might race against our setresuid(2) call. */
944 barrier_place(&barrier
);
946 /* Check if our parent process might already have
948 if (getppid() == parent_pid
) {
951 assert_se(sigemptyset(&ss
) >= 0);
952 assert_se(sigaddset(&ss
, SIGTERM
) >= 0);
955 if (sigwait(&ss
, &sig
) < 0) {
962 assert(sig
== SIGTERM
);
967 /* If our parent died we'll end the session */
968 if (getppid() != parent_pid
) {
969 pam_code
= pam_close_session(handle
, flags
);
970 if (pam_code
!= PAM_SUCCESS
)
977 pam_end(handle
, pam_code
| flags
);
981 barrier_set_role(&barrier
, BARRIER_PARENT
);
983 /* If the child was forked off successfully it will do all the
984 * cleanups, so forget about the handle here. */
987 /* Unblock SIGTERM again in the parent */
988 assert_se(sigprocmask(SIG_SETMASK
, &old_ss
, NULL
) >= 0);
990 /* We close the log explicitly here, since the PAM modules
991 * might have opened it, but we don't want this fd around. */
994 /* Synchronously wait for the child to initialize. We don't care for
995 * errors as we cannot recover. However, warn loudly if it happens. */
996 if (!barrier_place_and_sync(&barrier
))
997 log_error("PAM initialization failed");
1005 if (pam_code
!= PAM_SUCCESS
) {
1006 log_error("PAM failed: %s", pam_strerror(handle
, pam_code
));
1007 r
= -EPERM
; /* PAM errors do not map to errno */
1009 log_error_errno(r
, "PAM failed: %m");
1013 pam_code
= pam_close_session(handle
, flags
);
1015 pam_end(handle
, pam_code
| flags
);
1025 static void rename_process_from_path(const char *path
) {
1026 char process_name
[11];
1030 /* This resulting string must fit in 10 chars (i.e. the length
1031 * of "/sbin/init") to look pretty in /bin/ps */
1035 rename_process("(...)");
1041 /* The end of the process name is usually more
1042 * interesting, since the first bit might just be
1048 process_name
[0] = '(';
1049 memcpy(process_name
+1, p
, l
);
1050 process_name
[1+l
] = ')';
1051 process_name
[1+l
+1] = 0;
1053 rename_process(process_name
);
1058 static int apply_seccomp(const ExecContext
*c
) {
1059 uint32_t negative_action
, action
;
1060 scmp_filter_ctx
*seccomp
;
1067 negative_action
= c
->syscall_errno
== 0 ? SCMP_ACT_KILL
: SCMP_ACT_ERRNO(c
->syscall_errno
);
1069 seccomp
= seccomp_init(c
->syscall_whitelist
? negative_action
: SCMP_ACT_ALLOW
);
1073 if (c
->syscall_archs
) {
1075 SET_FOREACH(id
, c
->syscall_archs
, i
) {
1076 r
= seccomp_arch_add(seccomp
, PTR_TO_UINT32(id
) - 1);
1084 r
= seccomp_add_secondary_archs(seccomp
);
1089 action
= c
->syscall_whitelist
? SCMP_ACT_ALLOW
: negative_action
;
1090 SET_FOREACH(id
, c
->syscall_filter
, i
) {
1091 r
= seccomp_rule_add(seccomp
, action
, PTR_TO_INT(id
) - 1, 0);
1096 r
= seccomp_attr_set(seccomp
, SCMP_FLTATR_CTL_NNP
, 0);
1100 r
= seccomp_load(seccomp
);
1103 seccomp_release(seccomp
);
1107 static int apply_address_families(const ExecContext
*c
) {
1108 scmp_filter_ctx
*seccomp
;
1114 seccomp
= seccomp_init(SCMP_ACT_ALLOW
);
1118 r
= seccomp_add_secondary_archs(seccomp
);
1122 if (c
->address_families_whitelist
) {
1123 int af
, first
= 0, last
= 0;
1126 /* If this is a whitelist, we first block the address
1127 * families that are out of range and then everything
1128 * that is not in the set. First, we find the lowest
1129 * and highest address family in the set. */
1131 SET_FOREACH(afp
, c
->address_families
, i
) {
1132 af
= PTR_TO_INT(afp
);
1134 if (af
<= 0 || af
>= af_max())
1137 if (first
== 0 || af
< first
)
1140 if (last
== 0 || af
> last
)
1144 assert((first
== 0) == (last
== 0));
1148 /* No entries in the valid range, block everything */
1149 r
= seccomp_rule_add(
1151 SCMP_ACT_ERRNO(EPROTONOSUPPORT
),
1159 /* Block everything below the first entry */
1160 r
= seccomp_rule_add(
1162 SCMP_ACT_ERRNO(EPROTONOSUPPORT
),
1165 SCMP_A0(SCMP_CMP_LT
, first
));
1169 /* Block everything above the last entry */
1170 r
= seccomp_rule_add(
1172 SCMP_ACT_ERRNO(EPROTONOSUPPORT
),
1175 SCMP_A0(SCMP_CMP_GT
, last
));
1179 /* Block everything between the first and last
1181 for (af
= 1; af
< af_max(); af
++) {
1183 if (set_contains(c
->address_families
, INT_TO_PTR(af
)))
1186 r
= seccomp_rule_add(
1188 SCMP_ACT_ERRNO(EPROTONOSUPPORT
),
1191 SCMP_A0(SCMP_CMP_EQ
, af
));
1200 /* If this is a blacklist, then generate one rule for
1201 * each address family that are then combined in OR
1204 SET_FOREACH(af
, c
->address_families
, i
) {
1206 r
= seccomp_rule_add(
1208 SCMP_ACT_ERRNO(EPROTONOSUPPORT
),
1211 SCMP_A0(SCMP_CMP_EQ
, PTR_TO_INT(af
)));
1217 r
= seccomp_attr_set(seccomp
, SCMP_FLTATR_CTL_NNP
, 0);
1221 r
= seccomp_load(seccomp
);
1224 seccomp_release(seccomp
);
1228 static int apply_memory_deny_write_execute(const ExecContext
*c
) {
1229 scmp_filter_ctx
*seccomp
;
1234 seccomp
= seccomp_init(SCMP_ACT_ALLOW
);
1238 r
= seccomp_rule_add(
1240 SCMP_ACT_ERRNO(EPERM
),
1243 SCMP_A2(SCMP_CMP_MASKED_EQ
, PROT_EXEC
|PROT_WRITE
, PROT_EXEC
|PROT_WRITE
));
1247 r
= seccomp_rule_add(
1249 SCMP_ACT_ERRNO(EPERM
),
1252 SCMP_A2(SCMP_CMP_MASKED_EQ
, PROT_EXEC
, PROT_EXEC
));
1256 r
= seccomp_attr_set(seccomp
, SCMP_FLTATR_CTL_NNP
, 0);
1260 r
= seccomp_load(seccomp
);
1263 seccomp_release(seccomp
);
1267 static int apply_restrict_realtime(const ExecContext
*c
) {
1268 static const int permitted_policies
[] = {
1274 scmp_filter_ctx
*seccomp
;
1276 int r
, p
, max_policy
= 0;
1280 seccomp
= seccomp_init(SCMP_ACT_ALLOW
);
1284 /* Determine the highest policy constant we want to allow */
1285 for (i
= 0; i
< ELEMENTSOF(permitted_policies
); i
++)
1286 if (permitted_policies
[i
] > max_policy
)
1287 max_policy
= permitted_policies
[i
];
1289 /* Go through all policies with lower values than that, and block them -- unless they appear in the
1291 for (p
= 0; p
< max_policy
; p
++) {
1294 /* Check if this is in the whitelist. */
1295 for (i
= 0; i
< ELEMENTSOF(permitted_policies
); i
++)
1296 if (permitted_policies
[i
] == p
) {
1304 /* Deny this policy */
1305 r
= seccomp_rule_add(
1307 SCMP_ACT_ERRNO(EPERM
),
1308 SCMP_SYS(sched_setscheduler
),
1310 SCMP_A1(SCMP_CMP_EQ
, p
));
1315 /* Blacklist all other policies, i.e. the ones with higher values. Note that all comparisons are unsigned here,
1316 * hence no need no check for < 0 values. */
1317 r
= seccomp_rule_add(
1319 SCMP_ACT_ERRNO(EPERM
),
1320 SCMP_SYS(sched_setscheduler
),
1322 SCMP_A1(SCMP_CMP_GT
, max_policy
));
1326 r
= seccomp_attr_set(seccomp
, SCMP_FLTATR_CTL_NNP
, 0);
1330 r
= seccomp_load(seccomp
);
1333 seccomp_release(seccomp
);
1339 static void do_idle_pipe_dance(int idle_pipe
[4]) {
1343 idle_pipe
[1] = safe_close(idle_pipe
[1]);
1344 idle_pipe
[2] = safe_close(idle_pipe
[2]);
1346 if (idle_pipe
[0] >= 0) {
1349 r
= fd_wait_for_event(idle_pipe
[0], POLLHUP
, IDLE_TIMEOUT_USEC
);
1351 if (idle_pipe
[3] >= 0 && r
== 0 /* timeout */) {
1354 /* Signal systemd that we are bored and want to continue. */
1355 n
= write(idle_pipe
[3], "x", 1);
1357 /* Wait for systemd to react to the signal above. */
1358 fd_wait_for_event(idle_pipe
[0], POLLHUP
, IDLE_TIMEOUT2_USEC
);
1361 idle_pipe
[0] = safe_close(idle_pipe
[0]);
1365 idle_pipe
[3] = safe_close(idle_pipe
[3]);
1368 static int build_environment(
1369 const ExecContext
*c
,
1370 const ExecParameters
*p
,
1373 const char *username
,
1375 dev_t journal_stream_dev
,
1376 ino_t journal_stream_ino
,
1379 _cleanup_strv_free_
char **our_env
= NULL
;
1386 our_env
= new0(char*, 12);
1391 _cleanup_free_
char *joined
= NULL
;
1393 if (asprintf(&x
, "LISTEN_PID="PID_FMT
, getpid()) < 0)
1395 our_env
[n_env
++] = x
;
1397 if (asprintf(&x
, "LISTEN_FDS=%u", n_fds
) < 0)
1399 our_env
[n_env
++] = x
;
1401 joined
= strv_join(p
->fd_names
, ":");
1405 x
= strjoin("LISTEN_FDNAMES=", joined
, NULL
);
1408 our_env
[n_env
++] = x
;
1411 if (p
->watchdog_usec
> 0) {
1412 if (asprintf(&x
, "WATCHDOG_PID="PID_FMT
, getpid()) < 0)
1414 our_env
[n_env
++] = x
;
1416 if (asprintf(&x
, "WATCHDOG_USEC="USEC_FMT
, p
->watchdog_usec
) < 0)
1418 our_env
[n_env
++] = x
;
1422 x
= strappend("HOME=", home
);
1425 our_env
[n_env
++] = x
;
1429 x
= strappend("LOGNAME=", username
);
1432 our_env
[n_env
++] = x
;
1434 x
= strappend("USER=", username
);
1437 our_env
[n_env
++] = x
;
1441 x
= strappend("SHELL=", shell
);
1444 our_env
[n_env
++] = x
;
1447 if (is_terminal_input(c
->std_input
) ||
1448 c
->std_output
== EXEC_OUTPUT_TTY
||
1449 c
->std_error
== EXEC_OUTPUT_TTY
||
1452 x
= strdup(default_term_for_tty(exec_context_tty_path(c
)));
1455 our_env
[n_env
++] = x
;
1458 if (journal_stream_dev
!= 0 && journal_stream_ino
!= 0) {
1459 if (asprintf(&x
, "JOURNAL_STREAM=" DEV_FMT
":" INO_FMT
, journal_stream_dev
, journal_stream_ino
) < 0)
1462 our_env
[n_env
++] = x
;
1465 our_env
[n_env
++] = NULL
;
1466 assert(n_env
<= 12);
1474 static int build_pass_environment(const ExecContext
*c
, char ***ret
) {
1475 _cleanup_strv_free_
char **pass_env
= NULL
;
1476 size_t n_env
= 0, n_bufsize
= 0;
1479 STRV_FOREACH(i
, c
->pass_environment
) {
1480 _cleanup_free_
char *x
= NULL
;
1486 x
= strjoin(*i
, "=", v
, NULL
);
1489 if (!GREEDY_REALLOC(pass_env
, n_bufsize
, n_env
+ 2))
1491 pass_env
[n_env
++] = x
;
1492 pass_env
[n_env
] = NULL
;
1502 static bool exec_needs_mount_namespace(
1503 const ExecContext
*context
,
1504 const ExecParameters
*params
,
1505 ExecRuntime
*runtime
) {
1510 if (!strv_isempty(context
->read_write_paths
) ||
1511 !strv_isempty(context
->read_only_paths
) ||
1512 !strv_isempty(context
->inaccessible_paths
))
1515 if (context
->mount_flags
!= 0)
1518 if (context
->private_tmp
&& runtime
&& (runtime
->tmp_dir
|| runtime
->var_tmp_dir
))
1521 if (context
->private_devices
||
1522 context
->protect_system
!= PROTECT_SYSTEM_NO
||
1523 context
->protect_home
!= PROTECT_HOME_NO
)
1529 static int close_remaining_fds(
1530 const ExecParameters
*params
,
1531 ExecRuntime
*runtime
,
1533 int *fds
, unsigned n_fds
) {
1535 unsigned n_dont_close
= 0;
1536 int dont_close
[n_fds
+ 7];
1540 if (params
->stdin_fd
>= 0)
1541 dont_close
[n_dont_close
++] = params
->stdin_fd
;
1542 if (params
->stdout_fd
>= 0)
1543 dont_close
[n_dont_close
++] = params
->stdout_fd
;
1544 if (params
->stderr_fd
>= 0)
1545 dont_close
[n_dont_close
++] = params
->stderr_fd
;
1548 dont_close
[n_dont_close
++] = socket_fd
;
1550 memcpy(dont_close
+ n_dont_close
, fds
, sizeof(int) * n_fds
);
1551 n_dont_close
+= n_fds
;
1555 if (runtime
->netns_storage_socket
[0] >= 0)
1556 dont_close
[n_dont_close
++] = runtime
->netns_storage_socket
[0];
1557 if (runtime
->netns_storage_socket
[1] >= 0)
1558 dont_close
[n_dont_close
++] = runtime
->netns_storage_socket
[1];
1561 return close_all_fds(dont_close
, n_dont_close
);
1564 static int exec_child(
1566 ExecCommand
*command
,
1567 const ExecContext
*context
,
1568 const ExecParameters
*params
,
1569 ExecRuntime
*runtime
,
1572 int *fds
, unsigned n_fds
,
1576 _cleanup_strv_free_
char **our_env
= NULL
, **pass_env
= NULL
, **accum_env
= NULL
, **final_argv
= NULL
;
1577 _cleanup_free_
char *mac_selinux_context_net
= NULL
;
1578 const char *username
= NULL
, *home
= NULL
, *shell
= NULL
, *wd
;
1579 dev_t journal_stream_dev
= 0;
1580 ino_t journal_stream_ino
= 0;
1581 bool needs_mount_namespace
;
1582 uid_t uid
= UID_INVALID
;
1583 gid_t gid
= GID_INVALID
;
1590 assert(exit_status
);
1592 rename_process_from_path(command
->path
);
1594 /* We reset exactly these signals, since they are the
1595 * only ones we set to SIG_IGN in the main daemon. All
1596 * others we leave untouched because we set them to
1597 * SIG_DFL or a valid handler initially, both of which
1598 * will be demoted to SIG_DFL. */
1599 (void) default_signals(SIGNALS_CRASH_HANDLER
,
1600 SIGNALS_IGNORE
, -1);
1602 if (context
->ignore_sigpipe
)
1603 (void) ignore_signals(SIGPIPE
, -1);
1605 r
= reset_signal_mask();
1607 *exit_status
= EXIT_SIGNAL_MASK
;
1611 if (params
->idle_pipe
)
1612 do_idle_pipe_dance(params
->idle_pipe
);
1614 /* Close sockets very early to make sure we don't
1615 * block init reexecution because it cannot bind its
1620 r
= close_remaining_fds(params
, runtime
, socket_fd
, fds
, n_fds
);
1622 *exit_status
= EXIT_FDS
;
1626 if (!context
->same_pgrp
)
1628 *exit_status
= EXIT_SETSID
;
1632 exec_context_tty_reset(context
, params
);
1634 if (params
->confirm_spawn
) {
1637 r
= ask_for_confirmation(&response
, argv
);
1638 if (r
== -ETIMEDOUT
)
1639 write_confirm_message("Confirmation question timed out, assuming positive response.\n");
1641 write_confirm_message("Couldn't ask confirmation question, assuming positive response: %s\n", strerror(-r
));
1642 else if (response
== 's') {
1643 write_confirm_message("Skipping execution.\n");
1644 *exit_status
= EXIT_CONFIRM
;
1646 } else if (response
== 'n') {
1647 write_confirm_message("Failing execution.\n");
1653 if (context
->user
) {
1654 username
= context
->user
;
1655 r
= get_user_creds(&username
, &uid
, &gid
, &home
, &shell
);
1657 *exit_status
= EXIT_USER
;
1662 if (context
->group
) {
1663 const char *g
= context
->group
;
1665 r
= get_group_creds(&g
, &gid
);
1667 *exit_status
= EXIT_GROUP
;
1673 /* If a socket is connected to STDIN/STDOUT/STDERR, we
1674 * must sure to drop O_NONBLOCK */
1676 (void) fd_nonblock(socket_fd
, false);
1678 r
= setup_input(context
, params
, socket_fd
);
1680 *exit_status
= EXIT_STDIN
;
1684 r
= setup_output(unit
, context
, params
, STDOUT_FILENO
, socket_fd
, basename(command
->path
), uid
, gid
, &journal_stream_dev
, &journal_stream_ino
);
1686 *exit_status
= EXIT_STDOUT
;
1690 r
= setup_output(unit
, context
, params
, STDERR_FILENO
, socket_fd
, basename(command
->path
), uid
, gid
, &journal_stream_dev
, &journal_stream_ino
);
1692 *exit_status
= EXIT_STDERR
;
1696 if (params
->cgroup_path
) {
1697 r
= cg_attach_everywhere(params
->cgroup_supported
, params
->cgroup_path
, 0, NULL
, NULL
);
1699 *exit_status
= EXIT_CGROUP
;
1704 if (context
->oom_score_adjust_set
) {
1705 char t
[DECIMAL_STR_MAX(context
->oom_score_adjust
)];
1707 /* When we can't make this change due to EPERM, then
1708 * let's silently skip over it. User namespaces
1709 * prohibit write access to this file, and we
1710 * shouldn't trip up over that. */
1712 sprintf(t
, "%i", context
->oom_score_adjust
);
1713 r
= write_string_file("/proc/self/oom_score_adj", t
, 0);
1714 if (r
== -EPERM
|| r
== -EACCES
) {
1716 log_unit_debug_errno(unit
, r
, "Failed to adjust OOM setting, assuming containerized execution, ignoring: %m");
1719 *exit_status
= EXIT_OOM_ADJUST
;
1724 if (context
->nice_set
)
1725 if (setpriority(PRIO_PROCESS
, 0, context
->nice
) < 0) {
1726 *exit_status
= EXIT_NICE
;
1730 if (context
->cpu_sched_set
) {
1731 struct sched_param param
= {
1732 .sched_priority
= context
->cpu_sched_priority
,
1735 r
= sched_setscheduler(0,
1736 context
->cpu_sched_policy
|
1737 (context
->cpu_sched_reset_on_fork
?
1738 SCHED_RESET_ON_FORK
: 0),
1741 *exit_status
= EXIT_SETSCHEDULER
;
1746 if (context
->cpuset
)
1747 if (sched_setaffinity(0, CPU_ALLOC_SIZE(context
->cpuset_ncpus
), context
->cpuset
) < 0) {
1748 *exit_status
= EXIT_CPUAFFINITY
;
1752 if (context
->ioprio_set
)
1753 if (ioprio_set(IOPRIO_WHO_PROCESS
, 0, context
->ioprio
) < 0) {
1754 *exit_status
= EXIT_IOPRIO
;
1758 if (context
->timer_slack_nsec
!= NSEC_INFINITY
)
1759 if (prctl(PR_SET_TIMERSLACK
, context
->timer_slack_nsec
) < 0) {
1760 *exit_status
= EXIT_TIMERSLACK
;
1764 if (context
->personality
!= PERSONALITY_INVALID
)
1765 if (personality(context
->personality
) < 0) {
1766 *exit_status
= EXIT_PERSONALITY
;
1770 if (context
->utmp_id
)
1771 utmp_put_init_process(context
->utmp_id
, getpid(), getsid(0), context
->tty_path
,
1772 context
->utmp_mode
== EXEC_UTMP_INIT
? INIT_PROCESS
:
1773 context
->utmp_mode
== EXEC_UTMP_LOGIN
? LOGIN_PROCESS
:
1775 username
? "root" : context
->user
);
1777 if (context
->user
&& is_terminal_input(context
->std_input
)) {
1778 r
= chown_terminal(STDIN_FILENO
, uid
);
1780 *exit_status
= EXIT_STDIN
;
1785 /* If delegation is enabled we'll pass ownership of the cgroup
1786 * (but only in systemd's own controller hierarchy!) to the
1787 * user of the new process. */
1788 if (params
->cgroup_path
&& context
->user
&& params
->cgroup_delegate
) {
1789 r
= cg_set_task_access(SYSTEMD_CGROUP_CONTROLLER
, params
->cgroup_path
, 0644, uid
, gid
);
1791 *exit_status
= EXIT_CGROUP
;
1796 r
= cg_set_group_access(SYSTEMD_CGROUP_CONTROLLER
, params
->cgroup_path
, 0755, uid
, gid
);
1798 *exit_status
= EXIT_CGROUP
;
1803 if (!strv_isempty(context
->runtime_directory
) && params
->runtime_prefix
) {
1806 STRV_FOREACH(rt
, context
->runtime_directory
) {
1807 _cleanup_free_
char *p
;
1809 p
= strjoin(params
->runtime_prefix
, "/", *rt
, NULL
);
1811 *exit_status
= EXIT_RUNTIME_DIRECTORY
;
1815 r
= mkdir_p_label(p
, context
->runtime_directory_mode
);
1817 *exit_status
= EXIT_RUNTIME_DIRECTORY
;
1821 r
= chmod_and_chown(p
, context
->runtime_directory_mode
, uid
, gid
);
1823 *exit_status
= EXIT_RUNTIME_DIRECTORY
;
1829 r
= build_environment(
1840 *exit_status
= EXIT_MEMORY
;
1844 r
= build_pass_environment(context
, &pass_env
);
1846 *exit_status
= EXIT_MEMORY
;
1850 accum_env
= strv_env_merge(5,
1851 params
->environment
,
1854 context
->environment
,
1858 *exit_status
= EXIT_MEMORY
;
1861 accum_env
= strv_env_clean(accum_env
);
1863 umask(context
->umask
);
1865 if (params
->apply_permissions
&& !command
->privileged
) {
1866 r
= enforce_groups(context
, username
, gid
);
1868 *exit_status
= EXIT_GROUP
;
1872 if (context
->smack_process_label
) {
1873 r
= mac_smack_apply_pid(0, context
->smack_process_label
);
1875 *exit_status
= EXIT_SMACK_PROCESS_LABEL
;
1879 #ifdef SMACK_DEFAULT_PROCESS_LABEL
1881 _cleanup_free_
char *exec_label
= NULL
;
1883 r
= mac_smack_read(command
->path
, SMACK_ATTR_EXEC
, &exec_label
);
1884 if (r
< 0 && r
!= -ENODATA
&& r
!= -EOPNOTSUPP
) {
1885 *exit_status
= EXIT_SMACK_PROCESS_LABEL
;
1889 r
= mac_smack_apply_pid(0, exec_label
? : SMACK_DEFAULT_PROCESS_LABEL
);
1891 *exit_status
= EXIT_SMACK_PROCESS_LABEL
;
1898 if (context
->pam_name
&& username
) {
1899 r
= setup_pam(context
->pam_name
, username
, uid
, context
->tty_path
, &accum_env
, fds
, n_fds
);
1901 *exit_status
= EXIT_PAM
;
1908 if (context
->private_network
&& runtime
&& runtime
->netns_storage_socket
[0] >= 0) {
1909 r
= setup_netns(runtime
->netns_storage_socket
);
1911 *exit_status
= EXIT_NETWORK
;
1916 needs_mount_namespace
= exec_needs_mount_namespace(context
, params
, runtime
);
1918 if (needs_mount_namespace
) {
1919 char *tmp
= NULL
, *var
= NULL
;
1921 /* The runtime struct only contains the parent
1922 * of the private /tmp, which is
1923 * non-accessible to world users. Inside of it
1924 * there's a /tmp that is sticky, and that's
1925 * the one we want to use here. */
1927 if (context
->private_tmp
&& runtime
) {
1928 if (runtime
->tmp_dir
)
1929 tmp
= strjoina(runtime
->tmp_dir
, "/tmp");
1930 if (runtime
->var_tmp_dir
)
1931 var
= strjoina(runtime
->var_tmp_dir
, "/tmp");
1934 r
= setup_namespace(
1935 params
->apply_chroot
? context
->root_directory
: NULL
,
1936 context
->read_write_paths
,
1937 context
->read_only_paths
,
1938 context
->inaccessible_paths
,
1941 context
->private_devices
,
1942 context
->protect_home
,
1943 context
->protect_system
,
1944 context
->mount_flags
);
1946 /* If we couldn't set up the namespace this is
1947 * probably due to a missing capability. In this case,
1948 * silently proceeed. */
1949 if (r
== -EPERM
|| r
== -EACCES
) {
1951 log_unit_debug_errno(unit
, r
, "Failed to set up namespace, assuming containerized execution, ignoring: %m");
1954 *exit_status
= EXIT_NAMESPACE
;
1959 if (context
->working_directory_home
)
1961 else if (context
->working_directory
)
1962 wd
= context
->working_directory
;
1966 if (params
->apply_chroot
) {
1967 if (!needs_mount_namespace
&& context
->root_directory
)
1968 if (chroot(context
->root_directory
) < 0) {
1969 *exit_status
= EXIT_CHROOT
;
1973 if (chdir(wd
) < 0 &&
1974 !context
->working_directory_missing_ok
) {
1975 *exit_status
= EXIT_CHDIR
;
1981 d
= strjoina(strempty(context
->root_directory
), "/", strempty(wd
));
1983 !context
->working_directory_missing_ok
) {
1984 *exit_status
= EXIT_CHDIR
;
1990 if (params
->apply_permissions
&& mac_selinux_use() && params
->selinux_context_net
&& socket_fd
>= 0 && !command
->privileged
) {
1991 r
= mac_selinux_get_child_mls_label(socket_fd
, command
->path
, context
->selinux_context
, &mac_selinux_context_net
);
1993 *exit_status
= EXIT_SELINUX_CONTEXT
;
1999 /* We repeat the fd closing here, to make sure that
2000 * nothing is leaked from the PAM modules. Note that
2001 * we are more aggressive this time since socket_fd
2002 * and the netns fds we don't need anymore. The custom
2003 * endpoint fd was needed to upload the policy and can
2004 * now be closed as well. */
2005 r
= close_all_fds(fds
, n_fds
);
2007 r
= shift_fds(fds
, n_fds
);
2009 r
= flags_fds(fds
, n_fds
, context
->non_blocking
);
2011 *exit_status
= EXIT_FDS
;
2015 if (params
->apply_permissions
&& !command
->privileged
) {
2017 bool use_address_families
= context
->address_families_whitelist
||
2018 !set_isempty(context
->address_families
);
2019 bool use_syscall_filter
= context
->syscall_whitelist
||
2020 !set_isempty(context
->syscall_filter
) ||
2021 !set_isempty(context
->syscall_archs
);
2022 int secure_bits
= context
->secure_bits
;
2024 for (i
= 0; i
< _RLIMIT_MAX
; i
++) {
2026 if (!context
->rlimit
[i
])
2029 r
= setrlimit_closest(i
, context
->rlimit
[i
]);
2031 *exit_status
= EXIT_LIMITS
;
2036 /* Set the RTPRIO resource limit to 0, but only if nothing else was explicitly requested. */
2037 if (context
->restrict_realtime
&& !context
->rlimit
[RLIMIT_RTPRIO
]) {
2038 if (setrlimit(RLIMIT_RTPRIO
, &RLIMIT_MAKE_CONST(0)) < 0) {
2039 *exit_status
= EXIT_LIMITS
;
2044 if (!cap_test_all(context
->capability_bounding_set
)) {
2045 r
= capability_bounding_set_drop(context
->capability_bounding_set
, false);
2047 *exit_status
= EXIT_CAPABILITIES
;
2052 /* This is done before enforce_user, but ambient set
2053 * does not survive over setresuid() if keep_caps is not set. */
2054 if (context
->capability_ambient_set
!= 0) {
2055 r
= capability_ambient_set_apply(context
->capability_ambient_set
, true);
2057 *exit_status
= EXIT_CAPABILITIES
;
2062 if (context
->user
) {
2063 r
= enforce_user(context
, uid
);
2065 *exit_status
= EXIT_USER
;
2068 if (context
->capability_ambient_set
!= 0) {
2070 /* Fix the ambient capabilities after user change. */
2071 r
= capability_ambient_set_apply(context
->capability_ambient_set
, false);
2073 *exit_status
= EXIT_CAPABILITIES
;
2077 /* If we were asked to change user and ambient capabilities
2078 * were requested, we had to add keep-caps to the securebits
2079 * so that we would maintain the inherited capability set
2080 * through the setresuid(). Make sure that the bit is added
2081 * also to the context secure_bits so that we don't try to
2082 * drop the bit away next. */
2084 secure_bits
|= 1<<SECURE_KEEP_CAPS
;
2088 /* PR_GET_SECUREBITS is not privileged, while
2089 * PR_SET_SECUREBITS is. So to suppress
2090 * potential EPERMs we'll try not to call
2091 * PR_SET_SECUREBITS unless necessary. */
2092 if (prctl(PR_GET_SECUREBITS
) != secure_bits
)
2093 if (prctl(PR_SET_SECUREBITS
, secure_bits
) < 0) {
2094 *exit_status
= EXIT_SECUREBITS
;
2098 if (context
->no_new_privileges
||
2099 (!have_effective_cap(CAP_SYS_ADMIN
) && (use_address_families
|| context
->memory_deny_write_execute
|| context
->restrict_realtime
|| use_syscall_filter
)))
2100 if (prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0) < 0) {
2101 *exit_status
= EXIT_NO_NEW_PRIVILEGES
;
2106 if (use_address_families
) {
2107 r
= apply_address_families(context
);
2109 *exit_status
= EXIT_ADDRESS_FAMILIES
;
2114 if (context
->memory_deny_write_execute
) {
2115 r
= apply_memory_deny_write_execute(context
);
2117 *exit_status
= EXIT_SECCOMP
;
2122 if (context
->restrict_realtime
) {
2123 r
= apply_restrict_realtime(context
);
2125 *exit_status
= EXIT_SECCOMP
;
2130 if (use_syscall_filter
) {
2131 r
= apply_seccomp(context
);
2133 *exit_status
= EXIT_SECCOMP
;
2140 if (mac_selinux_use()) {
2141 char *exec_context
= mac_selinux_context_net
?: context
->selinux_context
;
2144 r
= setexeccon(exec_context
);
2146 *exit_status
= EXIT_SELINUX_CONTEXT
;
2153 #ifdef HAVE_APPARMOR
2154 if (context
->apparmor_profile
&& mac_apparmor_use()) {
2155 r
= aa_change_onexec(context
->apparmor_profile
);
2156 if (r
< 0 && !context
->apparmor_profile_ignore
) {
2157 *exit_status
= EXIT_APPARMOR_PROFILE
;
2164 final_argv
= replace_env_argv(argv
, accum_env
);
2166 *exit_status
= EXIT_MEMORY
;
2170 if (_unlikely_(log_get_max_level() >= LOG_DEBUG
)) {
2171 _cleanup_free_
char *line
;
2173 line
= exec_command_line(final_argv
);
2176 log_struct(LOG_DEBUG
,
2178 "EXECUTABLE=%s", command
->path
,
2179 LOG_UNIT_MESSAGE(unit
, "Executing: %s", line
),
2185 execve(command
->path
, final_argv
, accum_env
);
2186 *exit_status
= EXIT_EXEC
;
2190 int exec_spawn(Unit
*unit
,
2191 ExecCommand
*command
,
2192 const ExecContext
*context
,
2193 const ExecParameters
*params
,
2194 ExecRuntime
*runtime
,
2197 _cleanup_strv_free_
char **files_env
= NULL
;
2198 int *fds
= NULL
; unsigned n_fds
= 0;
2199 _cleanup_free_
char *line
= NULL
;
2209 assert(params
->fds
|| params
->n_fds
<= 0);
2211 if (context
->std_input
== EXEC_INPUT_SOCKET
||
2212 context
->std_output
== EXEC_OUTPUT_SOCKET
||
2213 context
->std_error
== EXEC_OUTPUT_SOCKET
) {
2215 if (params
->n_fds
!= 1) {
2216 log_unit_error(unit
, "Got more than one socket.");
2220 socket_fd
= params
->fds
[0];
2224 n_fds
= params
->n_fds
;
2227 r
= exec_context_load_environment(unit
, context
, &files_env
);
2229 return log_unit_error_errno(unit
, r
, "Failed to load environment files: %m");
2231 argv
= params
->argv
?: command
->argv
;
2232 line
= exec_command_line(argv
);
2236 log_struct(LOG_DEBUG
,
2238 LOG_UNIT_MESSAGE(unit
, "About to execute: %s", line
),
2239 "EXECUTABLE=%s", command
->path
,
2243 return log_unit_error_errno(unit
, errno
, "Failed to fork: %m");
2248 r
= exec_child(unit
,
2260 log_struct_errno(LOG_ERR
, r
,
2261 LOG_MESSAGE_ID(SD_MESSAGE_SPAWN_FAILED
),
2263 LOG_UNIT_MESSAGE(unit
, "Failed at step %s spawning %s: %m",
2264 exit_status_to_string(exit_status
, EXIT_STATUS_SYSTEMD
),
2266 "EXECUTABLE=%s", command
->path
,
2273 log_unit_debug(unit
, "Forked %s as "PID_FMT
, command
->path
, pid
);
2275 /* We add the new process to the cgroup both in the child (so
2276 * that we can be sure that no user code is ever executed
2277 * outside of the cgroup) and in the parent (so that we can be
2278 * sure that when we kill the cgroup the process will be
2280 if (params
->cgroup_path
)
2281 (void) cg_attach(SYSTEMD_CGROUP_CONTROLLER
, params
->cgroup_path
, pid
);
2283 exec_status_start(&command
->exec_status
, pid
);
2289 void exec_context_init(ExecContext
*c
) {
2293 c
->ioprio
= IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE
, 0);
2294 c
->cpu_sched_policy
= SCHED_OTHER
;
2295 c
->syslog_priority
= LOG_DAEMON
|LOG_INFO
;
2296 c
->syslog_level_prefix
= true;
2297 c
->ignore_sigpipe
= true;
2298 c
->timer_slack_nsec
= NSEC_INFINITY
;
2299 c
->personality
= PERSONALITY_INVALID
;
2300 c
->runtime_directory_mode
= 0755;
2301 c
->capability_bounding_set
= CAP_ALL
;
2304 void exec_context_done(ExecContext
*c
) {
2309 c
->environment
= strv_free(c
->environment
);
2310 c
->environment_files
= strv_free(c
->environment_files
);
2311 c
->pass_environment
= strv_free(c
->pass_environment
);
2313 for (l
= 0; l
< ELEMENTSOF(c
->rlimit
); l
++)
2314 c
->rlimit
[l
] = mfree(c
->rlimit
[l
]);
2316 c
->working_directory
= mfree(c
->working_directory
);
2317 c
->root_directory
= mfree(c
->root_directory
);
2318 c
->tty_path
= mfree(c
->tty_path
);
2319 c
->syslog_identifier
= mfree(c
->syslog_identifier
);
2320 c
->user
= mfree(c
->user
);
2321 c
->group
= mfree(c
->group
);
2323 c
->supplementary_groups
= strv_free(c
->supplementary_groups
);
2325 c
->pam_name
= mfree(c
->pam_name
);
2327 c
->read_only_paths
= strv_free(c
->read_only_paths
);
2328 c
->read_write_paths
= strv_free(c
->read_write_paths
);
2329 c
->inaccessible_paths
= strv_free(c
->inaccessible_paths
);
2332 CPU_FREE(c
->cpuset
);
2334 c
->utmp_id
= mfree(c
->utmp_id
);
2335 c
->selinux_context
= mfree(c
->selinux_context
);
2336 c
->apparmor_profile
= mfree(c
->apparmor_profile
);
2338 c
->syscall_filter
= set_free(c
->syscall_filter
);
2339 c
->syscall_archs
= set_free(c
->syscall_archs
);
2340 c
->address_families
= set_free(c
->address_families
);
2342 c
->runtime_directory
= strv_free(c
->runtime_directory
);
2345 int exec_context_destroy_runtime_directory(ExecContext
*c
, const char *runtime_prefix
) {
2350 if (!runtime_prefix
)
2353 STRV_FOREACH(i
, c
->runtime_directory
) {
2354 _cleanup_free_
char *p
;
2356 p
= strjoin(runtime_prefix
, "/", *i
, NULL
);
2360 /* We execute this synchronously, since we need to be
2361 * sure this is gone when we start the service
2363 (void) rm_rf(p
, REMOVE_ROOT
);
2369 void exec_command_done(ExecCommand
*c
) {
2372 c
->path
= mfree(c
->path
);
2374 c
->argv
= strv_free(c
->argv
);
2377 void exec_command_done_array(ExecCommand
*c
, unsigned n
) {
2380 for (i
= 0; i
< n
; i
++)
2381 exec_command_done(c
+i
);
2384 ExecCommand
* exec_command_free_list(ExecCommand
*c
) {
2388 LIST_REMOVE(command
, c
, i
);
2389 exec_command_done(i
);
2396 void exec_command_free_array(ExecCommand
**c
, unsigned n
) {
2399 for (i
= 0; i
< n
; i
++)
2400 c
[i
] = exec_command_free_list(c
[i
]);
2403 typedef struct InvalidEnvInfo
{
2408 static void invalid_env(const char *p
, void *userdata
) {
2409 InvalidEnvInfo
*info
= userdata
;
2411 log_unit_error(info
->unit
, "Ignoring invalid environment assignment '%s': %s", p
, info
->path
);
2414 int exec_context_load_environment(Unit
*unit
, const ExecContext
*c
, char ***l
) {
2415 char **i
, **r
= NULL
;
2420 STRV_FOREACH(i
, c
->environment_files
) {
2423 bool ignore
= false;
2425 _cleanup_globfree_ glob_t pglob
= {};
2435 if (!path_is_absolute(fn
)) {
2443 /* Filename supports globbing, take all matching files */
2445 if (glob(fn
, 0, NULL
, &pglob
) != 0) {
2450 return errno
> 0 ? -errno
: -EINVAL
;
2452 count
= pglob
.gl_pathc
;
2460 for (n
= 0; n
< count
; n
++) {
2461 k
= load_env_file(NULL
, pglob
.gl_pathv
[n
], NULL
, &p
);
2469 /* Log invalid environment variables with filename */
2471 InvalidEnvInfo info
= {
2473 .path
= pglob
.gl_pathv
[n
]
2476 p
= strv_env_clean_with_callback(p
, invalid_env
, &info
);
2484 m
= strv_env_merge(2, r
, p
);
2500 static bool tty_may_match_dev_console(const char *tty
) {
2501 _cleanup_free_
char *active
= NULL
;
2507 if (startswith(tty
, "/dev/"))
2510 /* trivial identity? */
2511 if (streq(tty
, "console"))
2514 console
= resolve_dev_console(&active
);
2515 /* if we could not resolve, assume it may */
2519 /* "tty0" means the active VC, so it may be the same sometimes */
2520 return streq(console
, tty
) || (streq(console
, "tty0") && tty_is_vc(tty
));
2523 bool exec_context_may_touch_console(ExecContext
*ec
) {
2525 return (ec
->tty_reset
||
2527 ec
->tty_vt_disallocate
||
2528 is_terminal_input(ec
->std_input
) ||
2529 is_terminal_output(ec
->std_output
) ||
2530 is_terminal_output(ec
->std_error
)) &&
2531 tty_may_match_dev_console(exec_context_tty_path(ec
));
2534 static void strv_fprintf(FILE *f
, char **l
) {
2540 fprintf(f
, " %s", *g
);
2543 void exec_context_dump(ExecContext
*c
, FILE* f
, const char *prefix
) {
2550 prefix
= strempty(prefix
);
2554 "%sWorkingDirectory: %s\n"
2555 "%sRootDirectory: %s\n"
2556 "%sNonBlocking: %s\n"
2557 "%sPrivateTmp: %s\n"
2558 "%sPrivateNetwork: %s\n"
2559 "%sPrivateDevices: %s\n"
2560 "%sProtectHome: %s\n"
2561 "%sProtectSystem: %s\n"
2562 "%sIgnoreSIGPIPE: %s\n"
2563 "%sMemoryDenyWriteExecute: %s\n"
2564 "%sRestrictRealtime: %s\n",
2566 prefix
, c
->working_directory
? c
->working_directory
: "/",
2567 prefix
, c
->root_directory
? c
->root_directory
: "/",
2568 prefix
, yes_no(c
->non_blocking
),
2569 prefix
, yes_no(c
->private_tmp
),
2570 prefix
, yes_no(c
->private_network
),
2571 prefix
, yes_no(c
->private_devices
),
2572 prefix
, protect_home_to_string(c
->protect_home
),
2573 prefix
, protect_system_to_string(c
->protect_system
),
2574 prefix
, yes_no(c
->ignore_sigpipe
),
2575 prefix
, yes_no(c
->memory_deny_write_execute
),
2576 prefix
, yes_no(c
->restrict_realtime
));
2578 STRV_FOREACH(e
, c
->environment
)
2579 fprintf(f
, "%sEnvironment: %s\n", prefix
, *e
);
2581 STRV_FOREACH(e
, c
->environment_files
)
2582 fprintf(f
, "%sEnvironmentFile: %s\n", prefix
, *e
);
2584 STRV_FOREACH(e
, c
->pass_environment
)
2585 fprintf(f
, "%sPassEnvironment: %s\n", prefix
, *e
);
2587 fprintf(f
, "%sRuntimeDirectoryMode: %04o\n", prefix
, c
->runtime_directory_mode
);
2589 STRV_FOREACH(d
, c
->runtime_directory
)
2590 fprintf(f
, "%sRuntimeDirectory: %s\n", prefix
, *d
);
2597 if (c
->oom_score_adjust_set
)
2599 "%sOOMScoreAdjust: %i\n",
2600 prefix
, c
->oom_score_adjust
);
2602 for (i
= 0; i
< RLIM_NLIMITS
; i
++)
2604 fprintf(f
, "%s%s: " RLIM_FMT
"\n",
2605 prefix
, rlimit_to_string(i
), c
->rlimit
[i
]->rlim_max
);
2606 fprintf(f
, "%s%sSoft: " RLIM_FMT
"\n",
2607 prefix
, rlimit_to_string(i
), c
->rlimit
[i
]->rlim_cur
);
2610 if (c
->ioprio_set
) {
2611 _cleanup_free_
char *class_str
= NULL
;
2613 ioprio_class_to_string_alloc(IOPRIO_PRIO_CLASS(c
->ioprio
), &class_str
);
2615 "%sIOSchedulingClass: %s\n"
2616 "%sIOPriority: %i\n",
2617 prefix
, strna(class_str
),
2618 prefix
, (int) IOPRIO_PRIO_DATA(c
->ioprio
));
2621 if (c
->cpu_sched_set
) {
2622 _cleanup_free_
char *policy_str
= NULL
;
2624 sched_policy_to_string_alloc(c
->cpu_sched_policy
, &policy_str
);
2626 "%sCPUSchedulingPolicy: %s\n"
2627 "%sCPUSchedulingPriority: %i\n"
2628 "%sCPUSchedulingResetOnFork: %s\n",
2629 prefix
, strna(policy_str
),
2630 prefix
, c
->cpu_sched_priority
,
2631 prefix
, yes_no(c
->cpu_sched_reset_on_fork
));
2635 fprintf(f
, "%sCPUAffinity:", prefix
);
2636 for (i
= 0; i
< c
->cpuset_ncpus
; i
++)
2637 if (CPU_ISSET_S(i
, CPU_ALLOC_SIZE(c
->cpuset_ncpus
), c
->cpuset
))
2638 fprintf(f
, " %u", i
);
2642 if (c
->timer_slack_nsec
!= NSEC_INFINITY
)
2643 fprintf(f
, "%sTimerSlackNSec: "NSEC_FMT
"\n", prefix
, c
->timer_slack_nsec
);
2646 "%sStandardInput: %s\n"
2647 "%sStandardOutput: %s\n"
2648 "%sStandardError: %s\n",
2649 prefix
, exec_input_to_string(c
->std_input
),
2650 prefix
, exec_output_to_string(c
->std_output
),
2651 prefix
, exec_output_to_string(c
->std_error
));
2657 "%sTTYVHangup: %s\n"
2658 "%sTTYVTDisallocate: %s\n",
2659 prefix
, c
->tty_path
,
2660 prefix
, yes_no(c
->tty_reset
),
2661 prefix
, yes_no(c
->tty_vhangup
),
2662 prefix
, yes_no(c
->tty_vt_disallocate
));
2664 if (c
->std_output
== EXEC_OUTPUT_SYSLOG
||
2665 c
->std_output
== EXEC_OUTPUT_KMSG
||
2666 c
->std_output
== EXEC_OUTPUT_JOURNAL
||
2667 c
->std_output
== EXEC_OUTPUT_SYSLOG_AND_CONSOLE
||
2668 c
->std_output
== EXEC_OUTPUT_KMSG_AND_CONSOLE
||
2669 c
->std_output
== EXEC_OUTPUT_JOURNAL_AND_CONSOLE
||
2670 c
->std_error
== EXEC_OUTPUT_SYSLOG
||
2671 c
->std_error
== EXEC_OUTPUT_KMSG
||
2672 c
->std_error
== EXEC_OUTPUT_JOURNAL
||
2673 c
->std_error
== EXEC_OUTPUT_SYSLOG_AND_CONSOLE
||
2674 c
->std_error
== EXEC_OUTPUT_KMSG_AND_CONSOLE
||
2675 c
->std_error
== EXEC_OUTPUT_JOURNAL_AND_CONSOLE
) {
2677 _cleanup_free_
char *fac_str
= NULL
, *lvl_str
= NULL
;
2679 log_facility_unshifted_to_string_alloc(c
->syslog_priority
>> 3, &fac_str
);
2680 log_level_to_string_alloc(LOG_PRI(c
->syslog_priority
), &lvl_str
);
2683 "%sSyslogFacility: %s\n"
2684 "%sSyslogLevel: %s\n",
2685 prefix
, strna(fac_str
),
2686 prefix
, strna(lvl_str
));
2690 fprintf(f
, "%sSecure Bits:%s%s%s%s%s%s\n",
2692 (c
->secure_bits
& 1<<SECURE_KEEP_CAPS
) ? " keep-caps" : "",
2693 (c
->secure_bits
& 1<<SECURE_KEEP_CAPS_LOCKED
) ? " keep-caps-locked" : "",
2694 (c
->secure_bits
& 1<<SECURE_NO_SETUID_FIXUP
) ? " no-setuid-fixup" : "",
2695 (c
->secure_bits
& 1<<SECURE_NO_SETUID_FIXUP_LOCKED
) ? " no-setuid-fixup-locked" : "",
2696 (c
->secure_bits
& 1<<SECURE_NOROOT
) ? " noroot" : "",
2697 (c
->secure_bits
& 1<<SECURE_NOROOT_LOCKED
) ? "noroot-locked" : "");
2699 if (c
->capability_bounding_set
!= CAP_ALL
) {
2701 fprintf(f
, "%sCapabilityBoundingSet:", prefix
);
2703 for (l
= 0; l
<= cap_last_cap(); l
++)
2704 if (c
->capability_bounding_set
& (UINT64_C(1) << l
))
2705 fprintf(f
, " %s", strna(capability_to_name(l
)));
2710 if (c
->capability_ambient_set
!= 0) {
2712 fprintf(f
, "%sAmbientCapabilities:", prefix
);
2714 for (l
= 0; l
<= cap_last_cap(); l
++)
2715 if (c
->capability_ambient_set
& (UINT64_C(1) << l
))
2716 fprintf(f
, " %s", strna(capability_to_name(l
)));
2722 fprintf(f
, "%sUser: %s\n", prefix
, c
->user
);
2724 fprintf(f
, "%sGroup: %s\n", prefix
, c
->group
);
2726 if (strv_length(c
->supplementary_groups
) > 0) {
2727 fprintf(f
, "%sSupplementaryGroups:", prefix
);
2728 strv_fprintf(f
, c
->supplementary_groups
);
2733 fprintf(f
, "%sPAMName: %s\n", prefix
, c
->pam_name
);
2735 if (strv_length(c
->read_write_paths
) > 0) {
2736 fprintf(f
, "%sReadWritePaths:", prefix
);
2737 strv_fprintf(f
, c
->read_write_paths
);
2741 if (strv_length(c
->read_only_paths
) > 0) {
2742 fprintf(f
, "%sReadOnlyPaths:", prefix
);
2743 strv_fprintf(f
, c
->read_only_paths
);
2747 if (strv_length(c
->inaccessible_paths
) > 0) {
2748 fprintf(f
, "%sInaccessiblePaths:", prefix
);
2749 strv_fprintf(f
, c
->inaccessible_paths
);
2755 "%sUtmpIdentifier: %s\n",
2756 prefix
, c
->utmp_id
);
2758 if (c
->selinux_context
)
2760 "%sSELinuxContext: %s%s\n",
2761 prefix
, c
->selinux_context_ignore
? "-" : "", c
->selinux_context
);
2763 if (c
->personality
!= PERSONALITY_INVALID
)
2765 "%sPersonality: %s\n",
2766 prefix
, strna(personality_to_string(c
->personality
)));
2768 if (c
->syscall_filter
) {
2776 "%sSystemCallFilter: ",
2779 if (!c
->syscall_whitelist
)
2783 SET_FOREACH(id
, c
->syscall_filter
, j
) {
2784 _cleanup_free_
char *name
= NULL
;
2791 name
= seccomp_syscall_resolve_num_arch(SCMP_ARCH_NATIVE
, PTR_TO_INT(id
) - 1);
2792 fputs(strna(name
), f
);
2799 if (c
->syscall_archs
) {
2806 "%sSystemCallArchitectures:",
2810 SET_FOREACH(id
, c
->syscall_archs
, j
)
2811 fprintf(f
, " %s", strna(seccomp_arch_to_string(PTR_TO_UINT32(id
) - 1)));
2816 if (c
->syscall_errno
> 0)
2818 "%sSystemCallErrorNumber: %s\n",
2819 prefix
, strna(errno_to_name(c
->syscall_errno
)));
2821 if (c
->apparmor_profile
)
2823 "%sAppArmorProfile: %s%s\n",
2824 prefix
, c
->apparmor_profile_ignore
? "-" : "", c
->apparmor_profile
);
2827 bool exec_context_maintains_privileges(ExecContext
*c
) {
2830 /* Returns true if the process forked off would run under
2831 * an unchanged UID or as root. */
2836 if (streq(c
->user
, "root") || streq(c
->user
, "0"))
2842 void exec_status_start(ExecStatus
*s
, pid_t pid
) {
2847 dual_timestamp_get(&s
->start_timestamp
);
2850 void exec_status_exit(ExecStatus
*s
, ExecContext
*context
, pid_t pid
, int code
, int status
) {
2853 if (s
->pid
&& s
->pid
!= pid
)
2857 dual_timestamp_get(&s
->exit_timestamp
);
2863 if (context
->utmp_id
)
2864 utmp_put_dead_process(context
->utmp_id
, pid
, code
, status
);
2866 exec_context_tty_reset(context
, NULL
);
2870 void exec_status_dump(ExecStatus
*s
, FILE *f
, const char *prefix
) {
2871 char buf
[FORMAT_TIMESTAMP_MAX
];
2879 prefix
= strempty(prefix
);
2882 "%sPID: "PID_FMT
"\n",
2885 if (s
->start_timestamp
.realtime
> 0)
2887 "%sStart Timestamp: %s\n",
2888 prefix
, format_timestamp(buf
, sizeof(buf
), s
->start_timestamp
.realtime
));
2890 if (s
->exit_timestamp
.realtime
> 0)
2892 "%sExit Timestamp: %s\n"
2894 "%sExit Status: %i\n",
2895 prefix
, format_timestamp(buf
, sizeof(buf
), s
->exit_timestamp
.realtime
),
2896 prefix
, sigchld_code_to_string(s
->code
),
2900 char *exec_command_line(char **argv
) {
2908 STRV_FOREACH(a
, argv
)
2911 if (!(n
= new(char, k
)))
2915 STRV_FOREACH(a
, argv
) {
2922 if (strpbrk(*a
, WHITESPACE
)) {
2933 /* FIXME: this doesn't really handle arguments that have
2934 * spaces and ticks in them */
2939 void exec_command_dump(ExecCommand
*c
, FILE *f
, const char *prefix
) {
2940 _cleanup_free_
char *cmd
= NULL
;
2941 const char *prefix2
;
2946 prefix
= strempty(prefix
);
2947 prefix2
= strjoina(prefix
, "\t");
2949 cmd
= exec_command_line(c
->argv
);
2951 "%sCommand Line: %s\n",
2952 prefix
, cmd
? cmd
: strerror(ENOMEM
));
2954 exec_status_dump(&c
->exec_status
, f
, prefix2
);
2957 void exec_command_dump_list(ExecCommand
*c
, FILE *f
, const char *prefix
) {
2960 prefix
= strempty(prefix
);
2962 LIST_FOREACH(command
, c
, c
)
2963 exec_command_dump(c
, f
, prefix
);
2966 void exec_command_append_list(ExecCommand
**l
, ExecCommand
*e
) {
2973 /* It's kind of important, that we keep the order here */
2974 LIST_FIND_TAIL(command
, *l
, end
);
2975 LIST_INSERT_AFTER(command
, *l
, end
, e
);
2980 int exec_command_set(ExecCommand
*c
, const char *path
, ...) {
2988 l
= strv_new_ap(path
, ap
);
3009 int exec_command_append(ExecCommand
*c
, const char *path
, ...) {
3010 _cleanup_strv_free_
char **l
= NULL
;
3018 l
= strv_new_ap(path
, ap
);
3024 r
= strv_extend_strv(&c
->argv
, l
, false);
3032 static int exec_runtime_allocate(ExecRuntime
**rt
) {
3037 *rt
= new0(ExecRuntime
, 1);
3042 (*rt
)->netns_storage_socket
[0] = (*rt
)->netns_storage_socket
[1] = -1;
3047 int exec_runtime_make(ExecRuntime
**rt
, ExecContext
*c
, const char *id
) {
3057 if (!c
->private_network
&& !c
->private_tmp
)
3060 r
= exec_runtime_allocate(rt
);
3064 if (c
->private_network
&& (*rt
)->netns_storage_socket
[0] < 0) {
3065 if (socketpair(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
, 0, (*rt
)->netns_storage_socket
) < 0)
3069 if (c
->private_tmp
&& !(*rt
)->tmp_dir
) {
3070 r
= setup_tmp_dirs(id
, &(*rt
)->tmp_dir
, &(*rt
)->var_tmp_dir
);
3078 ExecRuntime
*exec_runtime_ref(ExecRuntime
*r
) {
3080 assert(r
->n_ref
> 0);
3086 ExecRuntime
*exec_runtime_unref(ExecRuntime
*r
) {
3091 assert(r
->n_ref
> 0);
3098 free(r
->var_tmp_dir
);
3099 safe_close_pair(r
->netns_storage_socket
);
3105 int exec_runtime_serialize(Unit
*u
, ExecRuntime
*rt
, FILE *f
, FDSet
*fds
) {
3114 unit_serialize_item(u
, f
, "tmp-dir", rt
->tmp_dir
);
3116 if (rt
->var_tmp_dir
)
3117 unit_serialize_item(u
, f
, "var-tmp-dir", rt
->var_tmp_dir
);
3119 if (rt
->netns_storage_socket
[0] >= 0) {
3122 copy
= fdset_put_dup(fds
, rt
->netns_storage_socket
[0]);
3126 unit_serialize_item_format(u
, f
, "netns-socket-0", "%i", copy
);
3129 if (rt
->netns_storage_socket
[1] >= 0) {
3132 copy
= fdset_put_dup(fds
, rt
->netns_storage_socket
[1]);
3136 unit_serialize_item_format(u
, f
, "netns-socket-1", "%i", copy
);
3142 int exec_runtime_deserialize_item(Unit
*u
, ExecRuntime
**rt
, const char *key
, const char *value
, FDSet
*fds
) {
3149 if (streq(key
, "tmp-dir")) {
3152 r
= exec_runtime_allocate(rt
);
3156 copy
= strdup(value
);
3160 free((*rt
)->tmp_dir
);
3161 (*rt
)->tmp_dir
= copy
;
3163 } else if (streq(key
, "var-tmp-dir")) {
3166 r
= exec_runtime_allocate(rt
);
3170 copy
= strdup(value
);
3174 free((*rt
)->var_tmp_dir
);
3175 (*rt
)->var_tmp_dir
= copy
;
3177 } else if (streq(key
, "netns-socket-0")) {
3180 r
= exec_runtime_allocate(rt
);
3184 if (safe_atoi(value
, &fd
) < 0 || !fdset_contains(fds
, fd
))
3185 log_unit_debug(u
, "Failed to parse netns socket value: %s", value
);
3187 safe_close((*rt
)->netns_storage_socket
[0]);
3188 (*rt
)->netns_storage_socket
[0] = fdset_remove(fds
, fd
);
3190 } else if (streq(key
, "netns-socket-1")) {
3193 r
= exec_runtime_allocate(rt
);
3197 if (safe_atoi(value
, &fd
) < 0 || !fdset_contains(fds
, fd
))
3198 log_unit_debug(u
, "Failed to parse netns socket value: %s", value
);
3200 safe_close((*rt
)->netns_storage_socket
[1]);
3201 (*rt
)->netns_storage_socket
[1] = fdset_remove(fds
, fd
);
3209 static void *remove_tmpdir_thread(void *p
) {
3210 _cleanup_free_
char *path
= p
;
3212 (void) rm_rf(path
, REMOVE_ROOT
|REMOVE_PHYSICAL
);
3216 void exec_runtime_destroy(ExecRuntime
*rt
) {
3222 /* If there are multiple users of this, let's leave the stuff around */
3227 log_debug("Spawning thread to nuke %s", rt
->tmp_dir
);
3229 r
= asynchronous_job(remove_tmpdir_thread
, rt
->tmp_dir
);
3231 log_warning_errno(r
, "Failed to nuke %s: %m", rt
->tmp_dir
);
3238 if (rt
->var_tmp_dir
) {
3239 log_debug("Spawning thread to nuke %s", rt
->var_tmp_dir
);
3241 r
= asynchronous_job(remove_tmpdir_thread
, rt
->var_tmp_dir
);
3243 log_warning_errno(r
, "Failed to nuke %s: %m", rt
->var_tmp_dir
);
3244 free(rt
->var_tmp_dir
);
3247 rt
->var_tmp_dir
= NULL
;
3250 safe_close_pair(rt
->netns_storage_socket
);
3253 static const char* const exec_input_table
[_EXEC_INPUT_MAX
] = {
3254 [EXEC_INPUT_NULL
] = "null",
3255 [EXEC_INPUT_TTY
] = "tty",
3256 [EXEC_INPUT_TTY_FORCE
] = "tty-force",
3257 [EXEC_INPUT_TTY_FAIL
] = "tty-fail",
3258 [EXEC_INPUT_SOCKET
] = "socket"
3261 DEFINE_STRING_TABLE_LOOKUP(exec_input
, ExecInput
);
3263 static const char* const exec_output_table
[_EXEC_OUTPUT_MAX
] = {
3264 [EXEC_OUTPUT_INHERIT
] = "inherit",
3265 [EXEC_OUTPUT_NULL
] = "null",
3266 [EXEC_OUTPUT_TTY
] = "tty",
3267 [EXEC_OUTPUT_SYSLOG
] = "syslog",
3268 [EXEC_OUTPUT_SYSLOG_AND_CONSOLE
] = "syslog+console",
3269 [EXEC_OUTPUT_KMSG
] = "kmsg",
3270 [EXEC_OUTPUT_KMSG_AND_CONSOLE
] = "kmsg+console",
3271 [EXEC_OUTPUT_JOURNAL
] = "journal",
3272 [EXEC_OUTPUT_JOURNAL_AND_CONSOLE
] = "journal+console",
3273 [EXEC_OUTPUT_SOCKET
] = "socket"
3276 DEFINE_STRING_TABLE_LOOKUP(exec_output
, ExecOutput
);
3278 static const char* const exec_utmp_mode_table
[_EXEC_UTMP_MODE_MAX
] = {
3279 [EXEC_UTMP_INIT
] = "init",
3280 [EXEC_UTMP_LOGIN
] = "login",
3281 [EXEC_UTMP_USER
] = "user",
3284 DEFINE_STRING_TABLE_LOOKUP(exec_utmp_mode
, ExecUtmpMode
);