1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
29 #include <sys/socket.h>
31 #include <sys/prctl.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
37 #include <sys/mount.h>
41 #include <security/pam_appl.h>
50 #include "securebits.h"
52 #include "namespace.h"
55 /* This assumes there is a 'tty' group */
58 static int shift_fds(int fds[], unsigned n_fds) {
59 int start, restart_from;
64 /* Modifies the fds array! (sorts it) */
74 for (i = start; i < (int) n_fds; i++) {
77 /* Already at right index? */
81 if ((nfd = fcntl(fds[i], F_DUPFD, i+3)) < 0)
84 close_nointr_nofail(fds[i]);
87 /* Hmm, the fd we wanted isn't free? Then
88 * let's remember that and try again from here*/
89 if (nfd != i+3 && restart_from < 0)
102 static int flags_fds(const int fds[], unsigned n_fds, bool nonblock) {
111 /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags */
113 for (i = 0; i < n_fds; i++) {
115 if ((r = fd_nonblock(fds[i], nonblock)) < 0)
118 /* We unconditionally drop FD_CLOEXEC from the fds,
119 * since after all we want to pass these fds to our
122 if ((r = fd_cloexec(fds[i], false)) < 0)
129 static const char *tty_path(const ExecContext *context) {
132 if (context->tty_path)
133 return context->tty_path;
135 return "/dev/console";
138 static int open_null_as(int flags, int nfd) {
143 if ((fd = open("/dev/null", flags|O_NOCTTY)) < 0)
147 r = dup2(fd, nfd) < 0 ? -errno : nfd;
148 close_nointr_nofail(fd);
155 static int connect_logger_as(const ExecContext *context, ExecOutput output, const char *ident, int nfd) {
159 struct sockaddr_un un;
163 assert(output < _EXEC_OUTPUT_MAX);
167 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
171 sa.sa.sa_family = AF_UNIX;
172 strncpy(sa.un.sun_path+1, LOGGER_SOCKET, sizeof(sa.un.sun_path)-1);
174 if (connect(fd, &sa.sa, sizeof(sa)) < 0) {
175 close_nointr_nofail(fd);
179 if (shutdown(fd, SHUT_RD) < 0) {
180 close_nointr_nofail(fd);
184 /* We speak a very simple protocol between log server
185 * and client: one line for the log destination (kmsg
186 * or syslog), followed by the priority field,
187 * followed by the process name. Since we replaced
188 * stdin/stderr we simple use stdio to write to
189 * it. Note that we use stderr, to minimize buffer
190 * flushing issues. */
197 output == EXEC_OUTPUT_KMSG ? "kmsg" : "syslog",
198 context->syslog_priority,
199 context->syslog_identifier ? context->syslog_identifier : ident,
200 context->syslog_level_prefix);
203 r = dup2(fd, nfd) < 0 ? -errno : nfd;
204 close_nointr_nofail(fd);
210 static int open_terminal_as(const char *path, mode_t mode, int nfd) {
216 if ((fd = open_terminal(path, mode | O_NOCTTY)) < 0)
220 r = dup2(fd, nfd) < 0 ? -errno : nfd;
221 close_nointr_nofail(fd);
228 static bool is_terminal_input(ExecInput i) {
230 i == EXEC_INPUT_TTY ||
231 i == EXEC_INPUT_TTY_FORCE ||
232 i == EXEC_INPUT_TTY_FAIL;
235 static int fixup_input(ExecInput std_input, int socket_fd, bool apply_tty_stdin) {
237 if (is_terminal_input(std_input) && !apply_tty_stdin)
238 return EXEC_INPUT_NULL;
240 if (std_input == EXEC_INPUT_SOCKET && socket_fd < 0)
241 return EXEC_INPUT_NULL;
246 static int fixup_output(ExecOutput std_output, int socket_fd) {
248 if (std_output == EXEC_OUTPUT_SOCKET && socket_fd < 0)
249 return EXEC_OUTPUT_INHERIT;
254 static int setup_input(const ExecContext *context, int socket_fd, bool apply_tty_stdin) {
259 i = fixup_input(context->std_input, socket_fd, apply_tty_stdin);
263 case EXEC_INPUT_NULL:
264 return open_null_as(O_RDONLY, STDIN_FILENO);
267 case EXEC_INPUT_TTY_FORCE:
268 case EXEC_INPUT_TTY_FAIL: {
271 if ((fd = acquire_terminal(
273 i == EXEC_INPUT_TTY_FAIL,
274 i == EXEC_INPUT_TTY_FORCE,
278 if (fd != STDIN_FILENO) {
279 r = dup2(fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
280 close_nointr_nofail(fd);
287 case EXEC_INPUT_SOCKET:
288 return dup2(socket_fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
291 assert_not_reached("Unknown input type");
295 static int setup_output(const ExecContext *context, int socket_fd, const char *ident, bool apply_tty_stdin) {
302 i = fixup_input(context->std_input, socket_fd, apply_tty_stdin);
303 o = fixup_output(context->std_output, socket_fd);
305 /* This expects the input is already set up */
309 case EXEC_OUTPUT_INHERIT:
311 /* If the input is connected to anything that's not a /dev/null, inherit that... */
312 if (i != EXEC_INPUT_NULL)
313 return dup2(STDIN_FILENO, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
315 /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */
317 return STDOUT_FILENO;
319 /* We need to open /dev/null here anew, to get the
320 * right access mode. So we fall through */
322 case EXEC_OUTPUT_NULL:
323 return open_null_as(O_WRONLY, STDOUT_FILENO);
325 case EXEC_OUTPUT_TTY:
326 if (is_terminal_input(i))
327 return dup2(STDIN_FILENO, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
329 /* We don't reset the terminal if this is just about output */
330 return open_terminal_as(tty_path(context), O_WRONLY, STDOUT_FILENO);
332 case EXEC_OUTPUT_SYSLOG:
333 case EXEC_OUTPUT_KMSG:
334 return connect_logger_as(context, o, ident, STDOUT_FILENO);
336 case EXEC_OUTPUT_SOCKET:
337 assert(socket_fd >= 0);
338 return dup2(socket_fd, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
341 assert_not_reached("Unknown output type");
345 static int setup_error(const ExecContext *context, int socket_fd, const char *ident, bool apply_tty_stdin) {
352 i = fixup_input(context->std_input, socket_fd, apply_tty_stdin);
353 o = fixup_output(context->std_output, socket_fd);
354 e = fixup_output(context->std_error, socket_fd);
356 /* This expects the input and output are already set up */
358 /* Don't change the stderr file descriptor if we inherit all
359 * the way and are not on a tty */
360 if (e == EXEC_OUTPUT_INHERIT &&
361 o == EXEC_OUTPUT_INHERIT &&
362 i == EXEC_INPUT_NULL &&
364 return STDERR_FILENO;
366 /* Duplicate form stdout if possible */
367 if (e == o || e == EXEC_OUTPUT_INHERIT)
368 return dup2(STDOUT_FILENO, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
372 case EXEC_OUTPUT_NULL:
373 return open_null_as(O_WRONLY, STDERR_FILENO);
375 case EXEC_OUTPUT_TTY:
376 if (is_terminal_input(i))
377 return dup2(STDIN_FILENO, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
379 /* We don't reset the terminal if this is just about output */
380 return open_terminal_as(tty_path(context), O_WRONLY, STDERR_FILENO);
382 case EXEC_OUTPUT_SYSLOG:
383 case EXEC_OUTPUT_KMSG:
384 return connect_logger_as(context, e, ident, STDERR_FILENO);
386 case EXEC_OUTPUT_SOCKET:
387 assert(socket_fd >= 0);
388 return dup2(socket_fd, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
391 assert_not_reached("Unknown error type");
395 static int chown_terminal(int fd, uid_t uid) {
400 /* This might fail. What matters are the results. */
401 (void) fchown(fd, uid, -1);
402 (void) fchmod(fd, TTY_MODE);
404 if (fstat(fd, &st) < 0)
407 if (st.st_uid != uid || (st.st_mode & 0777) != TTY_MODE)
413 static int setup_confirm_stdio(const ExecContext *context,
415 int *_saved_stdout) {
416 int fd = -1, saved_stdin, saved_stdout = -1, r;
419 assert(_saved_stdin);
420 assert(_saved_stdout);
422 /* This returns positive EXIT_xxx return values instead of
423 * negative errno style values! */
425 if ((saved_stdin = fcntl(STDIN_FILENO, F_DUPFD, 3)) < 0)
428 if ((saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD, 3)) < 0) {
433 if ((fd = acquire_terminal(
435 context->std_input == EXEC_INPUT_TTY_FAIL,
436 context->std_input == EXEC_INPUT_TTY_FORCE,
442 if (chown_terminal(fd, getuid()) < 0) {
447 if (dup2(fd, STDIN_FILENO) < 0) {
452 if (dup2(fd, STDOUT_FILENO) < 0) {
458 close_nointr_nofail(fd);
460 *_saved_stdin = saved_stdin;
461 *_saved_stdout = saved_stdout;
466 if (saved_stdout >= 0)
467 close_nointr_nofail(saved_stdout);
469 if (saved_stdin >= 0)
470 close_nointr_nofail(saved_stdin);
473 close_nointr_nofail(fd);
478 static int restore_confirm_stdio(const ExecContext *context,
486 assert(*saved_stdin >= 0);
487 assert(saved_stdout);
488 assert(*saved_stdout >= 0);
490 /* This returns positive EXIT_xxx return values instead of
491 * negative errno style values! */
493 if (is_terminal_input(context->std_input)) {
495 /* The service wants terminal input. */
499 context->std_output == EXEC_OUTPUT_INHERIT ||
500 context->std_output == EXEC_OUTPUT_TTY;
503 /* If the service doesn't want a controlling terminal,
504 * then we need to get rid entirely of what we have
507 if (release_terminal() < 0)
510 if (dup2(*saved_stdin, STDIN_FILENO) < 0)
513 if (dup2(*saved_stdout, STDOUT_FILENO) < 0)
516 *keep_stdout = *keep_stdin = false;
522 static int get_group_creds(const char *groupname, gid_t *gid) {
529 /* We enforce some special rules for gid=0: in order to avoid
530 * NSS lookups for root we hardcode its data. */
532 if (streq(groupname, "root") || streq(groupname, "0")) {
537 if (safe_atolu(groupname, &lu) >= 0) {
539 g = getgrgid((gid_t) lu);
542 g = getgrnam(groupname);
546 return errno != 0 ? -errno : -ESRCH;
552 static int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
562 /* We enforce some special rules for uid=0: in order to avoid
563 * NSS lookups for root we hardcode its data. */
565 if (streq(*username, "root") || streq(*username, "0")) {
573 if (safe_atolu(*username, &lu) >= 0) {
575 p = getpwuid((uid_t) lu);
577 /* If there are multiple users with the same id, make
578 * sure to leave $USER to the configured value instead
579 * of the first occurence in the database. However if
580 * the uid was configured by a numeric uid, then let's
581 * pick the real username from /etc/passwd. */
583 *username = p->pw_name;
586 p = getpwnam(*username);
590 return errno != 0 ? -errno : -ESRCH;
598 static int enforce_groups(const ExecContext *context, const char *username, gid_t gid) {
599 bool keep_groups = false;
604 /* Lookup and ser GID and supplementary group list. Here too
605 * we avoid NSS lookups for gid=0. */
607 if (context->group || username) {
610 if ((r = get_group_creds(context->group, &gid)) < 0)
613 /* First step, initialize groups from /etc/groups */
614 if (username && gid != 0) {
615 if (initgroups(username, gid) < 0)
621 /* Second step, set our gids */
622 if (setresgid(gid, gid, gid) < 0)
626 if (context->supplementary_groups) {
631 /* Final step, initialize any manually set supplementary groups */
632 ngroups_max = (int) sysconf(_SC_NGROUPS_MAX);
634 if (!(gids = new(gid_t, ngroups_max)))
638 if ((k = getgroups(ngroups_max, gids)) < 0) {
645 STRV_FOREACH(i, context->supplementary_groups) {
647 if (k >= ngroups_max) {
652 if ((r = get_group_creds(*i, gids+k)) < 0) {
660 if (setgroups(k, gids) < 0) {
671 static int enforce_user(const ExecContext *context, uid_t uid) {
675 /* Sets (but doesn't lookup) the uid and make sure we keep the
676 * capabilities while doing so. */
678 if (context->capabilities) {
680 static const cap_value_t bits[] = {
681 CAP_SETUID, /* Necessary so that we can run setresuid() below */
682 CAP_SETPCAP /* Necessary so that we can set PR_SET_SECUREBITS later on */
685 /* First step: If we need to keep capabilities but
686 * drop privileges we need to make sure we keep our
687 * caps, whiel we drop priviliges. */
689 int sb = context->secure_bits|SECURE_KEEP_CAPS;
691 if (prctl(PR_GET_SECUREBITS) != sb)
692 if (prctl(PR_SET_SECUREBITS, sb) < 0)
696 /* Second step: set the capabilites. This will reduce
697 * the capabilities to the minimum we need. */
699 if (!(d = cap_dup(context->capabilities)))
702 if (cap_set_flag(d, CAP_EFFECTIVE, ELEMENTSOF(bits), bits, CAP_SET) < 0 ||
703 cap_set_flag(d, CAP_PERMITTED, ELEMENTSOF(bits), bits, CAP_SET) < 0) {
709 if (cap_set_proc(d) < 0) {
718 /* Third step: actually set the uids */
719 if (setresuid(uid, uid, uid) < 0)
722 /* At this point we should have all necessary capabilities but
723 are otherwise a normal user. However, the caps might got
724 corrupted due to the setresuid() so we need clean them up
725 later. This is done outside of this call. */
732 static int null_conv(
734 const struct pam_message **msg,
735 struct pam_response **resp,
738 /* We don't support conversations */
743 static int setup_pam(
748 int fds[], unsigned n_fds) {
750 static const struct pam_conv conv = {
755 pam_handle_t *handle = NULL;
757 int pam_code = PAM_SUCCESS;
759 bool close_session = false;
760 pid_t pam_pid = 0, parent_pid;
766 /* We set up PAM in the parent process, then fork. The child
767 * will then stay around untill killed via PR_GET_PDEATHSIG or
768 * systemd via the cgroup logic. It will then remove the PAM
769 * session again. The parent process will exec() the actual
770 * daemon. We do things this way to ensure that the main PID
771 * of the daemon is the one we initially fork()ed. */
773 if ((pam_code = pam_start(name, user, &conv, &handle)) != PAM_SUCCESS) {
779 if ((pam_code = pam_set_item(handle, PAM_TTY, tty)) != PAM_SUCCESS)
782 if ((pam_code = pam_acct_mgmt(handle, PAM_SILENT)) != PAM_SUCCESS)
785 if ((pam_code = pam_open_session(handle, PAM_SILENT)) != PAM_SUCCESS)
788 close_session = true;
790 if ((pam_code = pam_setcred(handle, PAM_ESTABLISH_CRED | PAM_SILENT)) != PAM_SUCCESS)
793 if ((!(e = pam_getenvlist(handle)))) {
794 pam_code = PAM_BUF_ERR;
798 /* Block SIGTERM, so that we know that it won't get lost in
800 if (sigemptyset(&ss) < 0 ||
801 sigaddset(&ss, SIGTERM) < 0 ||
802 sigprocmask(SIG_BLOCK, &ss, &old_ss) < 0)
805 parent_pid = getpid();
807 if ((pam_pid = fork()) < 0)
814 /* The child's job is to reset the PAM session on
817 /* This string must fit in 10 chars (i.e. the length
818 * of "/sbin/init") */
819 rename_process("sd:pam");
821 /* Make sure we don't keep open the passed fds in this
822 child. We assume that otherwise only those fds are
823 open here that have been opened by PAM. */
824 close_many(fds, n_fds);
826 /* Wait until our parent died. This will most likely
827 * not work since the kernel does not allow
828 * unpriviliged paretns kill their priviliged children
829 * this way. We rely on the control groups kill logic
830 * to do the rest for us. */
831 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
834 /* Check if our parent process might already have
836 if (getppid() == parent_pid) {
837 if (sigwait(&ss, &sig) < 0)
840 assert(sig == SIGTERM);
843 /* Only if our parent died we'll end the session */
844 if (getppid() != parent_pid)
845 if ((pam_code = pam_close_session(handle, PAM_DATA_SILENT)) != PAM_SUCCESS)
851 pam_end(handle, pam_code | PAM_DATA_SILENT);
855 /* If the child was forked off successfully it will do all the
856 * cleanups, so forget about the handle here. */
859 /* Unblock SIGSUR1 again in the parent */
860 if (sigprocmask(SIG_SETMASK, &old_ss, NULL) < 0)
863 /* We close the log explicitly here, since the PAM modules
864 * might have opened it, but we don't want this fd around. */
872 pam_code = pam_close_session(handle, PAM_DATA_SILENT);
874 pam_end(handle, pam_code | PAM_DATA_SILENT);
882 kill(pam_pid, SIGTERM);
888 int exec_spawn(ExecCommand *command,
890 const ExecContext *context,
891 int fds[], unsigned n_fds,
893 bool apply_permissions,
895 bool apply_tty_stdin,
897 CGroupBonding *cgroup_bondings,
908 assert(fds || n_fds <= 0);
910 if (context->std_input == EXEC_INPUT_SOCKET ||
911 context->std_output == EXEC_OUTPUT_SOCKET ||
912 context->std_error == EXEC_OUTPUT_SOCKET) {
925 argv = command->argv;
927 if (!(line = exec_command_line(argv)))
930 log_debug("About to execute: %s", line);
934 if ((r = cgroup_bonding_realize_list(cgroup_bondings)))
937 if ((pid = fork()) < 0)
943 const char *username = NULL, *home = NULL;
944 uid_t uid = (uid_t) -1;
945 gid_t gid = (gid_t) -1;
946 char **our_env = NULL, **pam_env = NULL, **final_env = NULL, **final_argv = NULL;
948 int saved_stdout = -1, saved_stdin = -1;
949 bool keep_stdout = false, keep_stdin = false;
953 /* This string must fit in 10 chars (i.e. the length
954 * of "/sbin/init") */
955 rename_process("sd:exec");
957 /* We reset exactly these signals, since they are the
958 * only ones we set to SIG_IGN in the main daemon. All
959 * others we leave untouched because we set them to
960 * SIG_DFL or a valid handler initially, both of which
961 * will be demoted to SIG_DFL. */
962 default_signals(SIGNALS_CRASH_HANDLER,
965 if (sigemptyset(&ss) < 0 ||
966 sigprocmask(SIG_SETMASK, &ss, NULL) < 0) {
967 r = EXIT_SIGNAL_MASK;
971 if (!context->same_pgrp)
977 if (context->tcpwrap_name) {
979 if (!socket_tcpwrap(socket_fd, context->tcpwrap_name)) {
984 for (i = 0; i < (int) n_fds; i++) {
985 if (!socket_tcpwrap(fds[i], context->tcpwrap_name)) {
992 /* We skip the confirmation step if we shall not apply the TTY */
994 (!is_terminal_input(context->std_input) || apply_tty_stdin)) {
997 /* Set up terminal for the question */
998 if ((r = setup_confirm_stdio(context,
999 &saved_stdin, &saved_stdout)))
1002 /* Now ask the question. */
1003 if (!(line = exec_command_line(argv))) {
1008 r = ask(&response, "yns", "Execute %s? [Yes, No, Skip] ", line);
1011 if (r < 0 || response == 'n') {
1014 } else if (response == 's') {
1019 /* Release terminal for the question */
1020 if ((r = restore_confirm_stdio(context,
1021 &saved_stdin, &saved_stdout,
1022 &keep_stdin, &keep_stdout)))
1027 if (setup_input(context, socket_fd, apply_tty_stdin) < 0) {
1033 if (setup_output(context, socket_fd, file_name_from_path(command->path), apply_tty_stdin) < 0) {
1038 if (setup_error(context, socket_fd, file_name_from_path(command->path), apply_tty_stdin) < 0) {
1043 if (cgroup_bondings)
1044 if ((r = cgroup_bonding_install_list(cgroup_bondings, 0)) < 0) {
1049 if (context->oom_adjust_set) {
1052 snprintf(t, sizeof(t), "%i", context->oom_adjust);
1055 if (write_one_line_file("/proc/self/oom_adj", t) < 0) {
1056 r = EXIT_OOM_ADJUST;
1061 if (context->nice_set)
1062 if (setpriority(PRIO_PROCESS, 0, context->nice) < 0) {
1067 if (context->cpu_sched_set) {
1068 struct sched_param param;
1071 param.sched_priority = context->cpu_sched_priority;
1073 if (sched_setscheduler(0, context->cpu_sched_policy |
1074 (context->cpu_sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0), ¶m) < 0) {
1075 r = EXIT_SETSCHEDULER;
1080 if (context->cpuset)
1081 if (sched_setaffinity(0, CPU_ALLOC_SIZE(context->cpuset_ncpus), context->cpuset) < 0) {
1082 r = EXIT_CPUAFFINITY;
1086 if (context->ioprio_set)
1087 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
1092 if (context->timer_slack_nsec_set)
1093 if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
1094 r = EXIT_TIMERSLACK;
1098 if (context->user) {
1099 username = context->user;
1100 if (get_user_creds(&username, &uid, &gid, &home) < 0) {
1105 if (is_terminal_input(context->std_input))
1106 if (chown_terminal(STDIN_FILENO, uid) < 0) {
1113 if (context->pam_name && username) {
1114 /* Make sure no fds leak into the PAM
1115 * supervisor process. We will call this later
1116 * on again to make sure that any fds leaked
1117 * by the PAM modules get closed before our
1119 if (close_all_fds(fds, n_fds) < 0) {
1124 if (setup_pam(context->pam_name, username, context->tty_path, &pam_env, fds, n_fds) < 0) {
1131 if (apply_permissions)
1132 if (enforce_groups(context, username, uid) < 0) {
1137 umask(context->umask);
1139 if (strv_length(context->read_write_dirs) > 0 ||
1140 strv_length(context->read_only_dirs) > 0 ||
1141 strv_length(context->inaccessible_dirs) > 0 ||
1142 context->mount_flags != MS_SHARED ||
1143 context->private_tmp)
1144 if ((r = setup_namespace(
1145 context->read_write_dirs,
1146 context->read_only_dirs,
1147 context->inaccessible_dirs,
1148 context->private_tmp,
1149 context->mount_flags)) < 0)
1153 if (context->root_directory)
1154 if (chroot(context->root_directory) < 0) {
1159 if (chdir(context->working_directory ? context->working_directory : "/") < 0) {
1167 if (asprintf(&d, "%s/%s",
1168 context->root_directory ? context->root_directory : "",
1169 context->working_directory ? context->working_directory : "") < 0) {
1183 if (close_all_fds(fds, n_fds) < 0 ||
1184 shift_fds(fds, n_fds) < 0 ||
1185 flags_fds(fds, n_fds, context->non_blocking) < 0) {
1190 if (apply_permissions) {
1192 for (i = 0; i < RLIMIT_NLIMITS; i++) {
1193 if (!context->rlimit[i])
1196 if (setrlimit(i, context->rlimit[i]) < 0) {
1203 if (enforce_user(context, uid) < 0) {
1208 /* PR_GET_SECUREBITS is not priviliged, while
1209 * PR_SET_SECUREBITS is. So to suppress
1210 * potential EPERMs we'll try not to call
1211 * PR_SET_SECUREBITS unless necessary. */
1212 if (prctl(PR_GET_SECUREBITS) != context->secure_bits)
1213 if (prctl(PR_SET_SECUREBITS, context->secure_bits) < 0) {
1214 r = EXIT_SECUREBITS;
1218 if (context->capabilities)
1219 if (cap_set_proc(context->capabilities) < 0) {
1220 r = EXIT_CAPABILITIES;
1225 if (!(our_env = new0(char*, 6))) {
1231 if (asprintf(our_env + n_env++, "LISTEN_PID=%lu", (unsigned long) getpid()) < 0 ||
1232 asprintf(our_env + n_env++, "LISTEN_FDS=%u", n_fds) < 0) {
1238 if (asprintf(our_env + n_env++, "HOME=%s", home) < 0) {
1244 if (asprintf(our_env + n_env++, "LOGNAME=%s", username) < 0 ||
1245 asprintf(our_env + n_env++, "USER=%s", username) < 0) {
1252 if (!(final_env = strv_env_merge(
1256 context->environment,
1263 if (!(final_argv = replace_env_argv(argv, final_env))) {
1268 execve(command->path, final_argv, final_env);
1273 strv_free(final_env);
1275 strv_free(final_argv);
1277 if (saved_stdin >= 0)
1278 close_nointr_nofail(saved_stdin);
1280 if (saved_stdout >= 0)
1281 close_nointr_nofail(saved_stdout);
1286 /* We add the new process to the cgroup both in the child (so
1287 * that we can be sure that no user code is ever executed
1288 * outside of the cgroup) and in the parent (so that we can be
1289 * sure that when we kill the cgroup the process will be
1291 if (cgroup_bondings)
1292 cgroup_bonding_install_list(cgroup_bondings, pid);
1294 log_debug("Forked %s as %lu", command->path, (unsigned long) pid);
1296 exec_status_start(&command->exec_status, pid);
1302 void exec_context_init(ExecContext *c) {
1306 c->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 0);
1307 c->cpu_sched_policy = SCHED_OTHER;
1308 c->syslog_priority = LOG_DAEMON|LOG_INFO;
1309 c->syslog_level_prefix = true;
1310 c->mount_flags = MS_SHARED;
1313 void exec_context_done(ExecContext *c) {
1318 strv_free(c->environment);
1319 c->environment = NULL;
1321 for (l = 0; l < ELEMENTSOF(c->rlimit); l++) {
1323 c->rlimit[l] = NULL;
1326 free(c->working_directory);
1327 c->working_directory = NULL;
1328 free(c->root_directory);
1329 c->root_directory = NULL;
1334 free(c->tcpwrap_name);
1335 c->tcpwrap_name = NULL;
1337 free(c->syslog_identifier);
1338 c->syslog_identifier = NULL;
1346 strv_free(c->supplementary_groups);
1347 c->supplementary_groups = NULL;
1352 if (c->capabilities) {
1353 cap_free(c->capabilities);
1354 c->capabilities = NULL;
1357 strv_free(c->read_only_dirs);
1358 c->read_only_dirs = NULL;
1360 strv_free(c->read_write_dirs);
1361 c->read_write_dirs = NULL;
1363 strv_free(c->inaccessible_dirs);
1364 c->inaccessible_dirs = NULL;
1367 CPU_FREE(c->cpuset);
1370 void exec_command_done(ExecCommand *c) {
1380 void exec_command_done_array(ExecCommand *c, unsigned n) {
1383 for (i = 0; i < n; i++)
1384 exec_command_done(c+i);
1387 void exec_command_free_list(ExecCommand *c) {
1391 LIST_REMOVE(ExecCommand, command, c, i);
1392 exec_command_done(i);
1397 void exec_command_free_array(ExecCommand **c, unsigned n) {
1400 for (i = 0; i < n; i++) {
1401 exec_command_free_list(c[i]);
1406 static void strv_fprintf(FILE *f, char **l) {
1412 fprintf(f, " %s", *g);
1415 void exec_context_dump(ExecContext *c, FILE* f, const char *prefix) {
1427 "%sWorkingDirectory: %s\n"
1428 "%sRootDirectory: %s\n"
1429 "%sNonBlocking: %s\n"
1430 "%sPrivateTmp: %s\n",
1432 prefix, c->working_directory ? c->working_directory : "/",
1433 prefix, c->root_directory ? c->root_directory : "/",
1434 prefix, yes_no(c->non_blocking),
1435 prefix, yes_no(c->private_tmp));
1438 for (e = c->environment; *e; e++)
1439 fprintf(f, "%sEnvironment: %s\n", prefix, *e);
1441 if (c->tcpwrap_name)
1443 "%sTCPWrapName: %s\n",
1444 prefix, c->tcpwrap_name);
1451 if (c->oom_adjust_set)
1453 "%sOOMAdjust: %i\n",
1454 prefix, c->oom_adjust);
1456 for (i = 0; i < RLIM_NLIMITS; i++)
1458 fprintf(f, "%s%s: %llu\n", prefix, rlimit_to_string(i), (unsigned long long) c->rlimit[i]->rlim_max);
1462 "%sIOSchedulingClass: %s\n"
1463 "%sIOPriority: %i\n",
1464 prefix, ioprio_class_to_string(IOPRIO_PRIO_CLASS(c->ioprio)),
1465 prefix, (int) IOPRIO_PRIO_DATA(c->ioprio));
1467 if (c->cpu_sched_set)
1469 "%sCPUSchedulingPolicy: %s\n"
1470 "%sCPUSchedulingPriority: %i\n"
1471 "%sCPUSchedulingResetOnFork: %s\n",
1472 prefix, sched_policy_to_string(c->cpu_sched_policy),
1473 prefix, c->cpu_sched_priority,
1474 prefix, yes_no(c->cpu_sched_reset_on_fork));
1477 fprintf(f, "%sCPUAffinity:", prefix);
1478 for (i = 0; i < c->cpuset_ncpus; i++)
1479 if (CPU_ISSET_S(i, CPU_ALLOC_SIZE(c->cpuset_ncpus), c->cpuset))
1480 fprintf(f, " %i", i);
1484 if (c->timer_slack_nsec_set)
1485 fprintf(f, "%sTimerSlackNSec: %lu\n", prefix, c->timer_slack_nsec);
1488 "%sStandardInput: %s\n"
1489 "%sStandardOutput: %s\n"
1490 "%sStandardError: %s\n",
1491 prefix, exec_input_to_string(c->std_input),
1492 prefix, exec_output_to_string(c->std_output),
1493 prefix, exec_output_to_string(c->std_error));
1498 prefix, c->tty_path);
1500 if (c->std_output == EXEC_OUTPUT_SYSLOG || c->std_output == EXEC_OUTPUT_KMSG ||
1501 c->std_error == EXEC_OUTPUT_SYSLOG || c->std_error == EXEC_OUTPUT_KMSG)
1503 "%sSyslogFacility: %s\n"
1504 "%sSyslogLevel: %s\n",
1505 prefix, log_facility_to_string(LOG_FAC(c->syslog_priority)),
1506 prefix, log_level_to_string(LOG_PRI(c->syslog_priority)));
1508 if (c->capabilities) {
1510 if ((t = cap_to_text(c->capabilities, NULL))) {
1511 fprintf(f, "%sCapabilities: %s\n",
1518 fprintf(f, "%sSecure Bits:%s%s%s%s%s%s\n",
1520 (c->secure_bits & SECURE_KEEP_CAPS) ? " keep-caps" : "",
1521 (c->secure_bits & SECURE_KEEP_CAPS_LOCKED) ? " keep-caps-locked" : "",
1522 (c->secure_bits & SECURE_NO_SETUID_FIXUP) ? " no-setuid-fixup" : "",
1523 (c->secure_bits & SECURE_NO_SETUID_FIXUP_LOCKED) ? " no-setuid-fixup-locked" : "",
1524 (c->secure_bits & SECURE_NOROOT) ? " noroot" : "",
1525 (c->secure_bits & SECURE_NOROOT_LOCKED) ? "noroot-locked" : "");
1527 if (c->capability_bounding_set_drop) {
1528 fprintf(f, "%sCapabilityBoundingSetDrop:", prefix);
1530 for (i = 0; i <= CAP_LAST_CAP; i++)
1531 if (c->capability_bounding_set_drop & (1 << i)) {
1534 if ((t = cap_to_name(i))) {
1535 fprintf(f, " %s", t);
1544 fprintf(f, "%sUser: %s\n", prefix, c->user);
1546 fprintf(f, "%sGroup: %s\n", prefix, c->group);
1548 if (strv_length(c->supplementary_groups) > 0) {
1549 fprintf(f, "%sSupplementaryGroups:", prefix);
1550 strv_fprintf(f, c->supplementary_groups);
1555 fprintf(f, "%sPAMName: %s\n", prefix, c->pam_name);
1557 if (strv_length(c->read_write_dirs) > 0) {
1558 fprintf(f, "%sReadWriteDirs:", prefix);
1559 strv_fprintf(f, c->read_write_dirs);
1563 if (strv_length(c->read_only_dirs) > 0) {
1564 fprintf(f, "%sReadOnlyDirs:", prefix);
1565 strv_fprintf(f, c->read_only_dirs);
1569 if (strv_length(c->inaccessible_dirs) > 0) {
1570 fprintf(f, "%sInaccessibleDirs:", prefix);
1571 strv_fprintf(f, c->inaccessible_dirs);
1576 void exec_status_start(ExecStatus *s, pid_t pid) {
1581 dual_timestamp_get(&s->start_timestamp);
1584 void exec_status_exit(ExecStatus *s, pid_t pid, int code, int status) {
1587 if ((s->pid && s->pid != pid) ||
1588 !s->start_timestamp.realtime <= 0)
1592 dual_timestamp_get(&s->exit_timestamp);
1598 void exec_status_dump(ExecStatus *s, FILE *f, const char *prefix) {
1599 char buf[FORMAT_TIMESTAMP_MAX];
1612 prefix, (unsigned long) s->pid);
1614 if (s->start_timestamp.realtime > 0)
1616 "%sStart Timestamp: %s\n",
1617 prefix, format_timestamp(buf, sizeof(buf), s->start_timestamp.realtime));
1619 if (s->exit_timestamp.realtime > 0)
1621 "%sExit Timestamp: %s\n"
1623 "%sExit Status: %i\n",
1624 prefix, format_timestamp(buf, sizeof(buf), s->exit_timestamp.realtime),
1625 prefix, sigchld_code_to_string(s->code),
1629 char *exec_command_line(char **argv) {
1637 STRV_FOREACH(a, argv)
1640 if (!(n = new(char, k)))
1644 STRV_FOREACH(a, argv) {
1651 if (strpbrk(*a, WHITESPACE)) {
1662 /* FIXME: this doesn't really handle arguments that have
1663 * spaces and ticks in them */
1668 void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
1670 const char *prefix2;
1679 p2 = strappend(prefix, "\t");
1680 prefix2 = p2 ? p2 : prefix;
1682 cmd = exec_command_line(c->argv);
1685 "%sCommand Line: %s\n",
1686 prefix, cmd ? cmd : strerror(ENOMEM));
1690 exec_status_dump(&c->exec_status, f, prefix2);
1695 void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
1701 LIST_FOREACH(command, c, c)
1702 exec_command_dump(c, f, prefix);
1705 void exec_command_append_list(ExecCommand **l, ExecCommand *e) {
1712 /* It's kinda important that we keep the order here */
1713 LIST_FIND_TAIL(ExecCommand, command, *l, end);
1714 LIST_INSERT_AFTER(ExecCommand, command, *l, end, e);
1719 int exec_command_set(ExecCommand *c, const char *path, ...) {
1727 l = strv_new_ap(path, ap);
1733 if (!(p = strdup(path))) {
1747 const char* exit_status_to_string(ExitStatus status) {
1749 /* We cast to int here, so that -Wenum doesn't complain that
1750 * EXIT_SUCCESS/EXIT_FAILURE aren't in the enum */
1752 switch ((int) status) {
1760 case EXIT_INVALIDARGUMENT:
1761 return "INVALIDARGUMENT";
1763 case EXIT_NOTIMPLEMENTED:
1764 return "NOTIMPLEMENTED";
1766 case EXIT_NOPERMISSION:
1767 return "NOPERMISSION";
1769 case EXIT_NOTINSTALLED:
1770 return "NOTINSSTALLED";
1772 case EXIT_NOTCONFIGURED:
1773 return "NOTCONFIGURED";
1775 case EXIT_NOTRUNNING:
1776 return "NOTRUNNING";
1796 case EXIT_OOM_ADJUST:
1797 return "OOM_ADJUST";
1799 case EXIT_SIGNAL_MASK:
1800 return "SIGNAL_MASK";
1814 case EXIT_TIMERSLACK:
1815 return "TIMERSLACK";
1817 case EXIT_SECUREBITS:
1818 return "SECUREBITS";
1820 case EXIT_SETSCHEDULER:
1821 return "SETSCHEDULER";
1823 case EXIT_CPUAFFINITY:
1824 return "CPUAFFINITY";
1832 case EXIT_CAPABILITIES:
1833 return "CAPABILITIES";
1858 static const char* const exec_input_table[_EXEC_INPUT_MAX] = {
1859 [EXEC_INPUT_NULL] = "null",
1860 [EXEC_INPUT_TTY] = "tty",
1861 [EXEC_INPUT_TTY_FORCE] = "tty-force",
1862 [EXEC_INPUT_TTY_FAIL] = "tty-fail",
1863 [EXEC_INPUT_SOCKET] = "socket"
1866 static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = {
1867 [EXEC_OUTPUT_INHERIT] = "inherit",
1868 [EXEC_OUTPUT_NULL] = "null",
1869 [EXEC_OUTPUT_TTY] = "tty",
1870 [EXEC_OUTPUT_SYSLOG] = "syslog",
1871 [EXEC_OUTPUT_KMSG] = "kmsg",
1872 [EXEC_OUTPUT_SOCKET] = "socket"
1875 DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput);
1877 DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput);