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_family_t) + 1 + sizeof(LOGGER_SOCKET) - 1) < 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 input got downgraded, inherit the original value */
312 if (i == EXEC_INPUT_NULL && is_terminal_input(context->std_input))
313 return open_terminal_as(tty_path(context), O_WRONLY, STDOUT_FILENO);
315 /* If the input is connected to anything that's not a /dev/null, inherit that... */
316 if (i != EXEC_INPUT_NULL)
317 return dup2(STDIN_FILENO, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
319 /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */
321 return STDOUT_FILENO;
323 /* We need to open /dev/null here anew, to get the
324 * right access mode. So we fall through */
326 case EXEC_OUTPUT_NULL:
327 return open_null_as(O_WRONLY, STDOUT_FILENO);
329 case EXEC_OUTPUT_TTY:
330 if (is_terminal_input(i))
331 return dup2(STDIN_FILENO, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
333 /* We don't reset the terminal if this is just about output */
334 return open_terminal_as(tty_path(context), O_WRONLY, STDOUT_FILENO);
336 case EXEC_OUTPUT_SYSLOG:
337 case EXEC_OUTPUT_KMSG:
338 return connect_logger_as(context, o, ident, STDOUT_FILENO);
340 case EXEC_OUTPUT_SOCKET:
341 assert(socket_fd >= 0);
342 return dup2(socket_fd, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
345 assert_not_reached("Unknown output type");
349 static int setup_error(const ExecContext *context, int socket_fd, const char *ident, bool apply_tty_stdin) {
356 i = fixup_input(context->std_input, socket_fd, apply_tty_stdin);
357 o = fixup_output(context->std_output, socket_fd);
358 e = fixup_output(context->std_error, socket_fd);
360 /* This expects the input and output are already set up */
362 /* Don't change the stderr file descriptor if we inherit all
363 * the way and are not on a tty */
364 if (e == EXEC_OUTPUT_INHERIT &&
365 o == EXEC_OUTPUT_INHERIT &&
366 i == EXEC_INPUT_NULL &&
367 !is_terminal_input(context->std_input) &&
369 return STDERR_FILENO;
371 /* Duplicate from stdout if possible */
372 if (e == o || e == EXEC_OUTPUT_INHERIT)
373 return dup2(STDOUT_FILENO, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
377 case EXEC_OUTPUT_NULL:
378 return open_null_as(O_WRONLY, STDERR_FILENO);
380 case EXEC_OUTPUT_TTY:
381 if (is_terminal_input(i))
382 return dup2(STDIN_FILENO, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
384 /* We don't reset the terminal if this is just about output */
385 return open_terminal_as(tty_path(context), O_WRONLY, STDERR_FILENO);
387 case EXEC_OUTPUT_SYSLOG:
388 case EXEC_OUTPUT_KMSG:
389 return connect_logger_as(context, e, ident, STDERR_FILENO);
391 case EXEC_OUTPUT_SOCKET:
392 assert(socket_fd >= 0);
393 return dup2(socket_fd, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
396 assert_not_reached("Unknown error type");
400 static int chown_terminal(int fd, uid_t uid) {
405 /* This might fail. What matters are the results. */
406 (void) fchown(fd, uid, -1);
407 (void) fchmod(fd, TTY_MODE);
409 if (fstat(fd, &st) < 0)
412 if (st.st_uid != uid || (st.st_mode & 0777) != TTY_MODE)
418 static int setup_confirm_stdio(const ExecContext *context,
420 int *_saved_stdout) {
421 int fd = -1, saved_stdin, saved_stdout = -1, r;
424 assert(_saved_stdin);
425 assert(_saved_stdout);
427 /* This returns positive EXIT_xxx return values instead of
428 * negative errno style values! */
430 if ((saved_stdin = fcntl(STDIN_FILENO, F_DUPFD, 3)) < 0)
433 if ((saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD, 3)) < 0) {
438 if ((fd = acquire_terminal(
440 context->std_input == EXEC_INPUT_TTY_FAIL,
441 context->std_input == EXEC_INPUT_TTY_FORCE,
447 if (chown_terminal(fd, getuid()) < 0) {
452 if (dup2(fd, STDIN_FILENO) < 0) {
457 if (dup2(fd, STDOUT_FILENO) < 0) {
463 close_nointr_nofail(fd);
465 *_saved_stdin = saved_stdin;
466 *_saved_stdout = saved_stdout;
471 if (saved_stdout >= 0)
472 close_nointr_nofail(saved_stdout);
474 if (saved_stdin >= 0)
475 close_nointr_nofail(saved_stdin);
478 close_nointr_nofail(fd);
483 static int restore_confirm_stdio(const ExecContext *context,
491 assert(*saved_stdin >= 0);
492 assert(saved_stdout);
493 assert(*saved_stdout >= 0);
495 /* This returns positive EXIT_xxx return values instead of
496 * negative errno style values! */
498 if (is_terminal_input(context->std_input)) {
500 /* The service wants terminal input. */
504 context->std_output == EXEC_OUTPUT_INHERIT ||
505 context->std_output == EXEC_OUTPUT_TTY;
508 /* If the service doesn't want a controlling terminal,
509 * then we need to get rid entirely of what we have
512 if (release_terminal() < 0)
515 if (dup2(*saved_stdin, STDIN_FILENO) < 0)
518 if (dup2(*saved_stdout, STDOUT_FILENO) < 0)
521 *keep_stdout = *keep_stdin = false;
527 static int get_group_creds(const char *groupname, gid_t *gid) {
534 /* We enforce some special rules for gid=0: in order to avoid
535 * NSS lookups for root we hardcode its data. */
537 if (streq(groupname, "root") || streq(groupname, "0")) {
542 if (safe_atolu(groupname, &lu) >= 0) {
544 g = getgrgid((gid_t) lu);
547 g = getgrnam(groupname);
551 return errno != 0 ? -errno : -ESRCH;
557 static int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
567 /* We enforce some special rules for uid=0: in order to avoid
568 * NSS lookups for root we hardcode its data. */
570 if (streq(*username, "root") || streq(*username, "0")) {
578 if (safe_atolu(*username, &lu) >= 0) {
580 p = getpwuid((uid_t) lu);
582 /* If there are multiple users with the same id, make
583 * sure to leave $USER to the configured value instead
584 * of the first occurence in the database. However if
585 * the uid was configured by a numeric uid, then let's
586 * pick the real username from /etc/passwd. */
588 *username = p->pw_name;
591 p = getpwnam(*username);
595 return errno != 0 ? -errno : -ESRCH;
603 static int enforce_groups(const ExecContext *context, const char *username, gid_t gid) {
604 bool keep_groups = false;
609 /* Lookup and ser GID and supplementary group list. Here too
610 * we avoid NSS lookups for gid=0. */
612 if (context->group || username) {
615 if ((r = get_group_creds(context->group, &gid)) < 0)
618 /* First step, initialize groups from /etc/groups */
619 if (username && gid != 0) {
620 if (initgroups(username, gid) < 0)
626 /* Second step, set our gids */
627 if (setresgid(gid, gid, gid) < 0)
631 if (context->supplementary_groups) {
636 /* Final step, initialize any manually set supplementary groups */
637 ngroups_max = (int) sysconf(_SC_NGROUPS_MAX);
639 if (!(gids = new(gid_t, ngroups_max)))
643 if ((k = getgroups(ngroups_max, gids)) < 0) {
650 STRV_FOREACH(i, context->supplementary_groups) {
652 if (k >= ngroups_max) {
657 if ((r = get_group_creds(*i, gids+k)) < 0) {
665 if (setgroups(k, gids) < 0) {
676 static int enforce_user(const ExecContext *context, uid_t uid) {
680 /* Sets (but doesn't lookup) the uid and make sure we keep the
681 * capabilities while doing so. */
683 if (context->capabilities) {
685 static const cap_value_t bits[] = {
686 CAP_SETUID, /* Necessary so that we can run setresuid() below */
687 CAP_SETPCAP /* Necessary so that we can set PR_SET_SECUREBITS later on */
690 /* First step: If we need to keep capabilities but
691 * drop privileges we need to make sure we keep our
692 * caps, whiel we drop priviliges. */
694 int sb = context->secure_bits|SECURE_KEEP_CAPS;
696 if (prctl(PR_GET_SECUREBITS) != sb)
697 if (prctl(PR_SET_SECUREBITS, sb) < 0)
701 /* Second step: set the capabilites. This will reduce
702 * the capabilities to the minimum we need. */
704 if (!(d = cap_dup(context->capabilities)))
707 if (cap_set_flag(d, CAP_EFFECTIVE, ELEMENTSOF(bits), bits, CAP_SET) < 0 ||
708 cap_set_flag(d, CAP_PERMITTED, ELEMENTSOF(bits), bits, CAP_SET) < 0) {
714 if (cap_set_proc(d) < 0) {
723 /* Third step: actually set the uids */
724 if (setresuid(uid, uid, uid) < 0)
727 /* At this point we should have all necessary capabilities but
728 are otherwise a normal user. However, the caps might got
729 corrupted due to the setresuid() so we need clean them up
730 later. This is done outside of this call. */
737 static int null_conv(
739 const struct pam_message **msg,
740 struct pam_response **resp,
743 /* We don't support conversations */
748 static int setup_pam(
753 int fds[], unsigned n_fds) {
755 static const struct pam_conv conv = {
760 pam_handle_t *handle = NULL;
762 int pam_code = PAM_SUCCESS;
764 bool close_session = false;
765 pid_t pam_pid = 0, parent_pid;
771 /* We set up PAM in the parent process, then fork. The child
772 * will then stay around untill killed via PR_GET_PDEATHSIG or
773 * systemd via the cgroup logic. It will then remove the PAM
774 * session again. The parent process will exec() the actual
775 * daemon. We do things this way to ensure that the main PID
776 * of the daemon is the one we initially fork()ed. */
778 if ((pam_code = pam_start(name, user, &conv, &handle)) != PAM_SUCCESS) {
784 if ((pam_code = pam_set_item(handle, PAM_TTY, tty)) != PAM_SUCCESS)
787 if ((pam_code = pam_acct_mgmt(handle, PAM_SILENT)) != PAM_SUCCESS)
790 if ((pam_code = pam_open_session(handle, PAM_SILENT)) != PAM_SUCCESS)
793 close_session = true;
795 if ((pam_code = pam_setcred(handle, PAM_ESTABLISH_CRED | PAM_SILENT)) != PAM_SUCCESS)
798 if ((!(e = pam_getenvlist(handle)))) {
799 pam_code = PAM_BUF_ERR;
803 /* Block SIGTERM, so that we know that it won't get lost in
805 if (sigemptyset(&ss) < 0 ||
806 sigaddset(&ss, SIGTERM) < 0 ||
807 sigprocmask(SIG_BLOCK, &ss, &old_ss) < 0)
810 parent_pid = getpid();
812 if ((pam_pid = fork()) < 0)
819 /* The child's job is to reset the PAM session on
822 /* This string must fit in 10 chars (i.e. the length
823 * of "/sbin/init") */
824 rename_process("sd:pam");
826 /* Make sure we don't keep open the passed fds in this
827 child. We assume that otherwise only those fds are
828 open here that have been opened by PAM. */
829 close_many(fds, n_fds);
831 /* Wait until our parent died. This will most likely
832 * not work since the kernel does not allow
833 * unpriviliged paretns kill their priviliged children
834 * this way. We rely on the control groups kill logic
835 * to do the rest for us. */
836 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
839 /* Check if our parent process might already have
841 if (getppid() == parent_pid) {
842 if (sigwait(&ss, &sig) < 0)
845 assert(sig == SIGTERM);
848 /* Only if our parent died we'll end the session */
849 if (getppid() != parent_pid)
850 if ((pam_code = pam_close_session(handle, PAM_DATA_SILENT)) != PAM_SUCCESS)
856 pam_end(handle, pam_code | PAM_DATA_SILENT);
860 /* If the child was forked off successfully it will do all the
861 * cleanups, so forget about the handle here. */
864 /* Unblock SIGSUR1 again in the parent */
865 if (sigprocmask(SIG_SETMASK, &old_ss, NULL) < 0)
868 /* We close the log explicitly here, since the PAM modules
869 * might have opened it, but we don't want this fd around. */
877 pam_code = pam_close_session(handle, PAM_DATA_SILENT);
879 pam_end(handle, pam_code | PAM_DATA_SILENT);
887 kill(pam_pid, SIGTERM);
893 int exec_spawn(ExecCommand *command,
895 const ExecContext *context,
896 int fds[], unsigned n_fds,
898 bool apply_permissions,
900 bool apply_tty_stdin,
902 CGroupBonding *cgroup_bondings,
913 assert(fds || n_fds <= 0);
915 if (context->std_input == EXEC_INPUT_SOCKET ||
916 context->std_output == EXEC_OUTPUT_SOCKET ||
917 context->std_error == EXEC_OUTPUT_SOCKET) {
930 argv = command->argv;
932 if (!(line = exec_command_line(argv)))
935 log_debug("About to execute: %s", line);
939 if ((r = cgroup_bonding_realize_list(cgroup_bondings)))
942 if ((pid = fork()) < 0)
948 const char *username = NULL, *home = NULL;
949 uid_t uid = (uid_t) -1;
950 gid_t gid = (gid_t) -1;
951 char **our_env = NULL, **pam_env = NULL, **final_env = NULL, **final_argv = NULL;
953 int saved_stdout = -1, saved_stdin = -1;
954 bool keep_stdout = false, keep_stdin = false;
958 /* This string must fit in 10 chars (i.e. the length
959 * of "/sbin/init") */
960 rename_process("sd:exec");
962 /* We reset exactly these signals, since they are the
963 * only ones we set to SIG_IGN in the main daemon. All
964 * others we leave untouched because we set them to
965 * SIG_DFL or a valid handler initially, both of which
966 * will be demoted to SIG_DFL. */
967 default_signals(SIGNALS_CRASH_HANDLER,
970 if (sigemptyset(&ss) < 0 ||
971 sigprocmask(SIG_SETMASK, &ss, NULL) < 0) {
972 r = EXIT_SIGNAL_MASK;
976 /* Close sockets very early to make sure we don't
977 * block init reexecution because it cannot bind its
979 if (close_all_fds(socket_fd >= 0 ? &socket_fd : fds,
980 socket_fd >= 0 ? 1 : n_fds) < 0) {
985 if (!context->same_pgrp)
991 if (context->tcpwrap_name) {
993 if (!socket_tcpwrap(socket_fd, context->tcpwrap_name)) {
998 for (i = 0; i < (int) n_fds; i++) {
999 if (!socket_tcpwrap(fds[i], context->tcpwrap_name)) {
1006 /* We skip the confirmation step if we shall not apply the TTY */
1007 if (confirm_spawn &&
1008 (!is_terminal_input(context->std_input) || apply_tty_stdin)) {
1011 /* Set up terminal for the question */
1012 if ((r = setup_confirm_stdio(context,
1013 &saved_stdin, &saved_stdout)))
1016 /* Now ask the question. */
1017 if (!(line = exec_command_line(argv))) {
1022 r = ask(&response, "yns", "Execute %s? [Yes, No, Skip] ", line);
1025 if (r < 0 || response == 'n') {
1028 } else if (response == 's') {
1033 /* Release terminal for the question */
1034 if ((r = restore_confirm_stdio(context,
1035 &saved_stdin, &saved_stdout,
1036 &keep_stdin, &keep_stdout)))
1041 if (setup_input(context, socket_fd, apply_tty_stdin) < 0) {
1047 if (setup_output(context, socket_fd, file_name_from_path(command->path), apply_tty_stdin) < 0) {
1052 if (setup_error(context, socket_fd, file_name_from_path(command->path), apply_tty_stdin) < 0) {
1057 if (cgroup_bondings)
1058 if ((r = cgroup_bonding_install_list(cgroup_bondings, 0)) < 0) {
1063 if (context->oom_adjust_set) {
1066 snprintf(t, sizeof(t), "%i", context->oom_adjust);
1069 if (write_one_line_file("/proc/self/oom_adj", t) < 0) {
1070 r = EXIT_OOM_ADJUST;
1075 if (context->nice_set)
1076 if (setpriority(PRIO_PROCESS, 0, context->nice) < 0) {
1081 if (context->cpu_sched_set) {
1082 struct sched_param param;
1085 param.sched_priority = context->cpu_sched_priority;
1087 if (sched_setscheduler(0, context->cpu_sched_policy |
1088 (context->cpu_sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0), ¶m) < 0) {
1089 r = EXIT_SETSCHEDULER;
1094 if (context->cpuset)
1095 if (sched_setaffinity(0, CPU_ALLOC_SIZE(context->cpuset_ncpus), context->cpuset) < 0) {
1096 r = EXIT_CPUAFFINITY;
1100 if (context->ioprio_set)
1101 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
1106 if (context->timer_slack_nsec_set)
1107 if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
1108 r = EXIT_TIMERSLACK;
1112 if (context->user) {
1113 username = context->user;
1114 if (get_user_creds(&username, &uid, &gid, &home) < 0) {
1119 if (is_terminal_input(context->std_input))
1120 if (chown_terminal(STDIN_FILENO, uid) < 0) {
1127 if (context->pam_name && username) {
1128 if (setup_pam(context->pam_name, username, context->tty_path, &pam_env, fds, n_fds) < 0) {
1135 if (apply_permissions)
1136 if (enforce_groups(context, username, uid) < 0) {
1141 umask(context->umask);
1143 if (strv_length(context->read_write_dirs) > 0 ||
1144 strv_length(context->read_only_dirs) > 0 ||
1145 strv_length(context->inaccessible_dirs) > 0 ||
1146 context->mount_flags != MS_SHARED ||
1147 context->private_tmp)
1148 if ((r = setup_namespace(
1149 context->read_write_dirs,
1150 context->read_only_dirs,
1151 context->inaccessible_dirs,
1152 context->private_tmp,
1153 context->mount_flags)) < 0)
1157 if (context->root_directory)
1158 if (chroot(context->root_directory) < 0) {
1163 if (chdir(context->working_directory ? context->working_directory : "/") < 0) {
1171 if (asprintf(&d, "%s/%s",
1172 context->root_directory ? context->root_directory : "",
1173 context->working_directory ? context->working_directory : "") < 0) {
1187 /* We repeat the fd closing here, to make sure that
1188 * nothing is leaked from the PAM modules */
1189 if (close_all_fds(fds, n_fds) < 0 ||
1190 shift_fds(fds, n_fds) < 0 ||
1191 flags_fds(fds, n_fds, context->non_blocking) < 0) {
1196 if (apply_permissions) {
1198 for (i = 0; i < RLIMIT_NLIMITS; i++) {
1199 if (!context->rlimit[i])
1202 if (setrlimit(i, context->rlimit[i]) < 0) {
1209 if (enforce_user(context, uid) < 0) {
1214 /* PR_GET_SECUREBITS is not priviliged, while
1215 * PR_SET_SECUREBITS is. So to suppress
1216 * potential EPERMs we'll try not to call
1217 * PR_SET_SECUREBITS unless necessary. */
1218 if (prctl(PR_GET_SECUREBITS) != context->secure_bits)
1219 if (prctl(PR_SET_SECUREBITS, context->secure_bits) < 0) {
1220 r = EXIT_SECUREBITS;
1224 if (context->capabilities)
1225 if (cap_set_proc(context->capabilities) < 0) {
1226 r = EXIT_CAPABILITIES;
1231 if (!(our_env = new0(char*, 6))) {
1237 if (asprintf(our_env + n_env++, "LISTEN_PID=%lu", (unsigned long) getpid()) < 0 ||
1238 asprintf(our_env + n_env++, "LISTEN_FDS=%u", n_fds) < 0) {
1244 if (asprintf(our_env + n_env++, "HOME=%s", home) < 0) {
1250 if (asprintf(our_env + n_env++, "LOGNAME=%s", username) < 0 ||
1251 asprintf(our_env + n_env++, "USER=%s", username) < 0) {
1258 if (!(final_env = strv_env_merge(
1262 context->environment,
1269 if (!(final_argv = replace_env_argv(argv, final_env))) {
1274 execve(command->path, final_argv, final_env);
1279 strv_free(final_env);
1281 strv_free(final_argv);
1283 if (saved_stdin >= 0)
1284 close_nointr_nofail(saved_stdin);
1286 if (saved_stdout >= 0)
1287 close_nointr_nofail(saved_stdout);
1292 /* We add the new process to the cgroup both in the child (so
1293 * that we can be sure that no user code is ever executed
1294 * outside of the cgroup) and in the parent (so that we can be
1295 * sure that when we kill the cgroup the process will be
1297 if (cgroup_bondings)
1298 cgroup_bonding_install_list(cgroup_bondings, pid);
1300 log_debug("Forked %s as %lu", command->path, (unsigned long) pid);
1302 exec_status_start(&command->exec_status, pid);
1308 void exec_context_init(ExecContext *c) {
1312 c->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 0);
1313 c->cpu_sched_policy = SCHED_OTHER;
1314 c->syslog_priority = LOG_DAEMON|LOG_INFO;
1315 c->syslog_level_prefix = true;
1316 c->mount_flags = MS_SHARED;
1317 c->kill_signal = SIGTERM;
1320 void exec_context_done(ExecContext *c) {
1325 strv_free(c->environment);
1326 c->environment = NULL;
1328 for (l = 0; l < ELEMENTSOF(c->rlimit); l++) {
1330 c->rlimit[l] = NULL;
1333 free(c->working_directory);
1334 c->working_directory = NULL;
1335 free(c->root_directory);
1336 c->root_directory = NULL;
1341 free(c->tcpwrap_name);
1342 c->tcpwrap_name = NULL;
1344 free(c->syslog_identifier);
1345 c->syslog_identifier = NULL;
1353 strv_free(c->supplementary_groups);
1354 c->supplementary_groups = NULL;
1359 if (c->capabilities) {
1360 cap_free(c->capabilities);
1361 c->capabilities = NULL;
1364 strv_free(c->read_only_dirs);
1365 c->read_only_dirs = NULL;
1367 strv_free(c->read_write_dirs);
1368 c->read_write_dirs = NULL;
1370 strv_free(c->inaccessible_dirs);
1371 c->inaccessible_dirs = NULL;
1374 CPU_FREE(c->cpuset);
1377 void exec_command_done(ExecCommand *c) {
1387 void exec_command_done_array(ExecCommand *c, unsigned n) {
1390 for (i = 0; i < n; i++)
1391 exec_command_done(c+i);
1394 void exec_command_free_list(ExecCommand *c) {
1398 LIST_REMOVE(ExecCommand, command, c, i);
1399 exec_command_done(i);
1404 void exec_command_free_array(ExecCommand **c, unsigned n) {
1407 for (i = 0; i < n; i++) {
1408 exec_command_free_list(c[i]);
1413 static void strv_fprintf(FILE *f, char **l) {
1419 fprintf(f, " %s", *g);
1422 void exec_context_dump(ExecContext *c, FILE* f, const char *prefix) {
1434 "%sWorkingDirectory: %s\n"
1435 "%sRootDirectory: %s\n"
1436 "%sNonBlocking: %s\n"
1437 "%sPrivateTmp: %s\n",
1439 prefix, c->working_directory ? c->working_directory : "/",
1440 prefix, c->root_directory ? c->root_directory : "/",
1441 prefix, yes_no(c->non_blocking),
1442 prefix, yes_no(c->private_tmp));
1445 for (e = c->environment; *e; e++)
1446 fprintf(f, "%sEnvironment: %s\n", prefix, *e);
1448 if (c->tcpwrap_name)
1450 "%sTCPWrapName: %s\n",
1451 prefix, c->tcpwrap_name);
1458 if (c->oom_adjust_set)
1460 "%sOOMAdjust: %i\n",
1461 prefix, c->oom_adjust);
1463 for (i = 0; i < RLIM_NLIMITS; i++)
1465 fprintf(f, "%s%s: %llu\n", prefix, rlimit_to_string(i), (unsigned long long) c->rlimit[i]->rlim_max);
1469 "%sIOSchedulingClass: %s\n"
1470 "%sIOPriority: %i\n",
1471 prefix, ioprio_class_to_string(IOPRIO_PRIO_CLASS(c->ioprio)),
1472 prefix, (int) IOPRIO_PRIO_DATA(c->ioprio));
1474 if (c->cpu_sched_set)
1476 "%sCPUSchedulingPolicy: %s\n"
1477 "%sCPUSchedulingPriority: %i\n"
1478 "%sCPUSchedulingResetOnFork: %s\n",
1479 prefix, sched_policy_to_string(c->cpu_sched_policy),
1480 prefix, c->cpu_sched_priority,
1481 prefix, yes_no(c->cpu_sched_reset_on_fork));
1484 fprintf(f, "%sCPUAffinity:", prefix);
1485 for (i = 0; i < c->cpuset_ncpus; i++)
1486 if (CPU_ISSET_S(i, CPU_ALLOC_SIZE(c->cpuset_ncpus), c->cpuset))
1487 fprintf(f, " %i", i);
1491 if (c->timer_slack_nsec_set)
1492 fprintf(f, "%sTimerSlackNSec: %lu\n", prefix, c->timer_slack_nsec);
1495 "%sStandardInput: %s\n"
1496 "%sStandardOutput: %s\n"
1497 "%sStandardError: %s\n",
1498 prefix, exec_input_to_string(c->std_input),
1499 prefix, exec_output_to_string(c->std_output),
1500 prefix, exec_output_to_string(c->std_error));
1505 prefix, c->tty_path);
1507 if (c->std_output == EXEC_OUTPUT_SYSLOG || c->std_output == EXEC_OUTPUT_KMSG ||
1508 c->std_error == EXEC_OUTPUT_SYSLOG || c->std_error == EXEC_OUTPUT_KMSG)
1510 "%sSyslogFacility: %s\n"
1511 "%sSyslogLevel: %s\n",
1512 prefix, log_facility_to_string(LOG_FAC(c->syslog_priority)),
1513 prefix, log_level_to_string(LOG_PRI(c->syslog_priority)));
1515 if (c->capabilities) {
1517 if ((t = cap_to_text(c->capabilities, NULL))) {
1518 fprintf(f, "%sCapabilities: %s\n",
1525 fprintf(f, "%sSecure Bits:%s%s%s%s%s%s\n",
1527 (c->secure_bits & SECURE_KEEP_CAPS) ? " keep-caps" : "",
1528 (c->secure_bits & SECURE_KEEP_CAPS_LOCKED) ? " keep-caps-locked" : "",
1529 (c->secure_bits & SECURE_NO_SETUID_FIXUP) ? " no-setuid-fixup" : "",
1530 (c->secure_bits & SECURE_NO_SETUID_FIXUP_LOCKED) ? " no-setuid-fixup-locked" : "",
1531 (c->secure_bits & SECURE_NOROOT) ? " noroot" : "",
1532 (c->secure_bits & SECURE_NOROOT_LOCKED) ? "noroot-locked" : "");
1534 if (c->capability_bounding_set_drop) {
1535 fprintf(f, "%sCapabilityBoundingSetDrop:", prefix);
1537 for (i = 0; i <= CAP_LAST_CAP; i++)
1538 if (c->capability_bounding_set_drop & (1 << i)) {
1541 if ((t = cap_to_name(i))) {
1542 fprintf(f, " %s", t);
1551 fprintf(f, "%sUser: %s\n", prefix, c->user);
1553 fprintf(f, "%sGroup: %s\n", prefix, c->group);
1555 if (strv_length(c->supplementary_groups) > 0) {
1556 fprintf(f, "%sSupplementaryGroups:", prefix);
1557 strv_fprintf(f, c->supplementary_groups);
1562 fprintf(f, "%sPAMName: %s\n", prefix, c->pam_name);
1564 if (strv_length(c->read_write_dirs) > 0) {
1565 fprintf(f, "%sReadWriteDirs:", prefix);
1566 strv_fprintf(f, c->read_write_dirs);
1570 if (strv_length(c->read_only_dirs) > 0) {
1571 fprintf(f, "%sReadOnlyDirs:", prefix);
1572 strv_fprintf(f, c->read_only_dirs);
1576 if (strv_length(c->inaccessible_dirs) > 0) {
1577 fprintf(f, "%sInaccessibleDirs:", prefix);
1578 strv_fprintf(f, c->inaccessible_dirs);
1584 "%sKillSignal: SIG%s\n",
1585 prefix, kill_mode_to_string(c->kill_mode),
1586 prefix, signal_to_string(c->kill_signal));
1589 void exec_status_start(ExecStatus *s, pid_t pid) {
1594 dual_timestamp_get(&s->start_timestamp);
1597 void exec_status_exit(ExecStatus *s, pid_t pid, int code, int status) {
1600 if ((s->pid && s->pid != pid) ||
1601 !s->start_timestamp.realtime <= 0)
1605 dual_timestamp_get(&s->exit_timestamp);
1611 void exec_status_dump(ExecStatus *s, FILE *f, const char *prefix) {
1612 char buf[FORMAT_TIMESTAMP_MAX];
1625 prefix, (unsigned long) s->pid);
1627 if (s->start_timestamp.realtime > 0)
1629 "%sStart Timestamp: %s\n",
1630 prefix, format_timestamp(buf, sizeof(buf), s->start_timestamp.realtime));
1632 if (s->exit_timestamp.realtime > 0)
1634 "%sExit Timestamp: %s\n"
1636 "%sExit Status: %i\n",
1637 prefix, format_timestamp(buf, sizeof(buf), s->exit_timestamp.realtime),
1638 prefix, sigchld_code_to_string(s->code),
1642 char *exec_command_line(char **argv) {
1650 STRV_FOREACH(a, argv)
1653 if (!(n = new(char, k)))
1657 STRV_FOREACH(a, argv) {
1664 if (strpbrk(*a, WHITESPACE)) {
1675 /* FIXME: this doesn't really handle arguments that have
1676 * spaces and ticks in them */
1681 void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
1683 const char *prefix2;
1692 p2 = strappend(prefix, "\t");
1693 prefix2 = p2 ? p2 : prefix;
1695 cmd = exec_command_line(c->argv);
1698 "%sCommand Line: %s\n",
1699 prefix, cmd ? cmd : strerror(ENOMEM));
1703 exec_status_dump(&c->exec_status, f, prefix2);
1708 void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
1714 LIST_FOREACH(command, c, c)
1715 exec_command_dump(c, f, prefix);
1718 void exec_command_append_list(ExecCommand **l, ExecCommand *e) {
1725 /* It's kinda important that we keep the order here */
1726 LIST_FIND_TAIL(ExecCommand, command, *l, end);
1727 LIST_INSERT_AFTER(ExecCommand, command, *l, end, e);
1732 int exec_command_set(ExecCommand *c, const char *path, ...) {
1740 l = strv_new_ap(path, ap);
1746 if (!(p = strdup(path))) {
1760 const char* exit_status_to_string(ExitStatus status) {
1762 /* We cast to int here, so that -Wenum doesn't complain that
1763 * EXIT_SUCCESS/EXIT_FAILURE aren't in the enum */
1765 switch ((int) status) {
1773 case EXIT_INVALIDARGUMENT:
1774 return "INVALIDARGUMENT";
1776 case EXIT_NOTIMPLEMENTED:
1777 return "NOTIMPLEMENTED";
1779 case EXIT_NOPERMISSION:
1780 return "NOPERMISSION";
1782 case EXIT_NOTINSTALLED:
1783 return "NOTINSSTALLED";
1785 case EXIT_NOTCONFIGURED:
1786 return "NOTCONFIGURED";
1788 case EXIT_NOTRUNNING:
1789 return "NOTRUNNING";
1809 case EXIT_OOM_ADJUST:
1810 return "OOM_ADJUST";
1812 case EXIT_SIGNAL_MASK:
1813 return "SIGNAL_MASK";
1827 case EXIT_TIMERSLACK:
1828 return "TIMERSLACK";
1830 case EXIT_SECUREBITS:
1831 return "SECUREBITS";
1833 case EXIT_SETSCHEDULER:
1834 return "SETSCHEDULER";
1836 case EXIT_CPUAFFINITY:
1837 return "CPUAFFINITY";
1845 case EXIT_CAPABILITIES:
1846 return "CAPABILITIES";
1871 static const char* const exec_input_table[_EXEC_INPUT_MAX] = {
1872 [EXEC_INPUT_NULL] = "null",
1873 [EXEC_INPUT_TTY] = "tty",
1874 [EXEC_INPUT_TTY_FORCE] = "tty-force",
1875 [EXEC_INPUT_TTY_FAIL] = "tty-fail",
1876 [EXEC_INPUT_SOCKET] = "socket"
1879 static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = {
1880 [EXEC_OUTPUT_INHERIT] = "inherit",
1881 [EXEC_OUTPUT_NULL] = "null",
1882 [EXEC_OUTPUT_TTY] = "tty",
1883 [EXEC_OUTPUT_SYSLOG] = "syslog",
1884 [EXEC_OUTPUT_KMSG] = "kmsg",
1885 [EXEC_OUTPUT_SOCKET] = "socket"
1888 DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput);
1890 DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput);