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_no_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) {
237 if (std_input == EXEC_INPUT_SOCKET && socket_fd < 0)
238 return EXEC_INPUT_NULL;
243 static int fixup_output(ExecOutput std_output, int socket_fd) {
245 if (std_output == EXEC_OUTPUT_SOCKET && socket_fd < 0)
246 return EXEC_OUTPUT_INHERIT;
251 static int setup_input(const ExecContext *context, int socket_fd) {
256 i = fixup_input(context->std_input, socket_fd);
260 case EXEC_INPUT_NULL:
261 return open_null_as(O_RDONLY, STDIN_FILENO);
264 case EXEC_INPUT_TTY_FORCE:
265 case EXEC_INPUT_TTY_FAIL: {
268 if ((fd = acquire_terminal(
270 i == EXEC_INPUT_TTY_FAIL,
271 i == EXEC_INPUT_TTY_FORCE,
275 if (fd != STDIN_FILENO) {
276 r = dup2(fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
277 close_nointr_nofail(fd);
284 case EXEC_INPUT_SOCKET:
285 return dup2(socket_fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
288 assert_not_reached("Unknown input type");
292 static int setup_output(const ExecContext *context, int socket_fd, const char *ident) {
299 i = fixup_input(context->std_input, socket_fd);
300 o = fixup_output(context->std_output, socket_fd);
302 /* This expects the input is already set up */
306 case EXEC_OUTPUT_INHERIT:
308 /* If the input is connected to a terminal, inherit that... */
309 if (i != EXEC_INPUT_NULL)
310 return dup2(STDIN_FILENO, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
312 /* For PID 1 stdout is always connected to /dev/null,
313 * hence reopen the console if out parent is PID1. */
315 return open_terminal_as(tty_path(context), O_WRONLY, STDOUT_FILENO);
317 return STDOUT_FILENO;
319 case EXEC_OUTPUT_NULL:
320 return open_null_as(O_WRONLY, STDOUT_FILENO);
322 case EXEC_OUTPUT_TTY:
323 if (is_terminal_input(i))
324 return dup2(STDIN_FILENO, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
326 /* We don't reset the terminal if this is just about output */
327 return open_terminal_as(tty_path(context), O_WRONLY, STDOUT_FILENO);
329 case EXEC_OUTPUT_SYSLOG:
330 case EXEC_OUTPUT_KMSG:
331 return connect_logger_as(context, o, ident, STDOUT_FILENO);
333 case EXEC_OUTPUT_SOCKET:
334 assert(socket_fd >= 0);
335 return dup2(socket_fd, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
338 assert_not_reached("Unknown output type");
342 static int setup_error(const ExecContext *context, int socket_fd, const char *ident) {
349 i = fixup_input(context->std_input, socket_fd);
350 o = fixup_output(context->std_output, socket_fd);
351 e = fixup_output(context->std_error, socket_fd);
353 /* This expects the input and output are already set up */
355 /* Don't change the stderr file descriptor if we inherit all
356 * the way and are not on a tty */
357 if (e == EXEC_OUTPUT_INHERIT &&
358 o == EXEC_OUTPUT_INHERIT &&
359 i != EXEC_INPUT_NULL &&
361 return STDERR_FILENO;
363 /* Duplicate form stdout if possible */
364 if (e == o || e == EXEC_OUTPUT_INHERIT)
365 return dup2(STDOUT_FILENO, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
369 case EXEC_OUTPUT_NULL:
370 return open_null_as(O_WRONLY, STDERR_FILENO);
372 case EXEC_OUTPUT_TTY:
373 if (is_terminal_input(i))
374 return dup2(STDIN_FILENO, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
376 /* We don't reset the terminal if this is just about output */
377 return open_terminal_as(tty_path(context), O_WRONLY, STDERR_FILENO);
379 case EXEC_OUTPUT_SYSLOG:
380 case EXEC_OUTPUT_KMSG:
381 return connect_logger_as(context, e, ident, STDERR_FILENO);
383 case EXEC_OUTPUT_SOCKET:
384 assert(socket_fd >= 0);
385 return dup2(socket_fd, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
388 assert_not_reached("Unknown error type");
392 static int chown_terminal(int fd, uid_t uid) {
397 /* This might fail. What matters are the results. */
398 (void) fchown(fd, uid, -1);
399 (void) fchmod(fd, TTY_MODE);
401 if (fstat(fd, &st) < 0)
404 if (st.st_uid != uid || (st.st_mode & 0777) != TTY_MODE)
410 static int setup_confirm_stdio(const ExecContext *context,
412 int *_saved_stdout) {
413 int fd = -1, saved_stdin, saved_stdout = -1, r;
416 assert(_saved_stdin);
417 assert(_saved_stdout);
419 /* This returns positive EXIT_xxx return values instead of
420 * negative errno style values! */
422 if ((saved_stdin = fcntl(STDIN_FILENO, F_DUPFD, 3)) < 0)
425 if ((saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD, 3)) < 0) {
430 if ((fd = acquire_terminal(
432 context->std_input == EXEC_INPUT_TTY_FAIL,
433 context->std_input == EXEC_INPUT_TTY_FORCE,
439 if (chown_terminal(fd, getuid()) < 0) {
444 if (dup2(fd, STDIN_FILENO) < 0) {
449 if (dup2(fd, STDOUT_FILENO) < 0) {
455 close_nointr_nofail(fd);
457 *_saved_stdin = saved_stdin;
458 *_saved_stdout = saved_stdout;
463 if (saved_stdout >= 0)
464 close_nointr_nofail(saved_stdout);
466 if (saved_stdin >= 0)
467 close_nointr_nofail(saved_stdin);
470 close_nointr_nofail(fd);
475 static int restore_confirm_stdio(const ExecContext *context,
483 assert(*saved_stdin >= 0);
484 assert(saved_stdout);
485 assert(*saved_stdout >= 0);
487 /* This returns positive EXIT_xxx return values instead of
488 * negative errno style values! */
490 if (is_terminal_input(context->std_input)) {
492 /* The service wants terminal input. */
496 context->std_output == EXEC_OUTPUT_INHERIT ||
497 context->std_output == EXEC_OUTPUT_TTY;
500 /* If the service doesn't want a controlling terminal,
501 * then we need to get rid entirely of what we have
504 if (release_terminal() < 0)
507 if (dup2(*saved_stdin, STDIN_FILENO) < 0)
510 if (dup2(*saved_stdout, STDOUT_FILENO) < 0)
513 *keep_stdout = *keep_stdin = false;
519 static int get_group_creds(const char *groupname, gid_t *gid) {
526 /* We enforce some special rules for gid=0: in order to avoid
527 * NSS lookups for root we hardcode its data. */
529 if (streq(groupname, "root") || streq(groupname, "0")) {
534 if (safe_atolu(groupname, &lu) >= 0) {
536 g = getgrgid((gid_t) lu);
539 g = getgrnam(groupname);
543 return errno != 0 ? -errno : -ESRCH;
549 static int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
559 /* We enforce some special rules for uid=0: in order to avoid
560 * NSS lookups for root we hardcode its data. */
562 if (streq(*username, "root") || streq(*username, "0")) {
570 if (safe_atolu(*username, &lu) >= 0) {
572 p = getpwuid((uid_t) lu);
574 /* If there are multiple users with the same id, make
575 * sure to leave $USER to the configured value instead
576 * of the first occurence in the database. However if
577 * the uid was configured by a numeric uid, then let's
578 * pick the real username from /etc/passwd. */
580 *username = p->pw_name;
583 p = getpwnam(*username);
587 return errno != 0 ? -errno : -ESRCH;
595 static int enforce_groups(const ExecContext *context, const char *username, gid_t gid) {
596 bool keep_groups = false;
601 /* Lookup and ser GID and supplementary group list. Here too
602 * we avoid NSS lookups for gid=0. */
604 if (context->group || username) {
607 if ((r = get_group_creds(context->group, &gid)) < 0)
610 /* First step, initialize groups from /etc/groups */
611 if (username && gid != 0) {
612 if (initgroups(username, gid) < 0)
618 /* Second step, set our gids */
619 if (setresgid(gid, gid, gid) < 0)
623 if (context->supplementary_groups) {
628 /* Final step, initialize any manually set supplementary groups */
629 ngroups_max = (int) sysconf(_SC_NGROUPS_MAX);
631 if (!(gids = new(gid_t, ngroups_max)))
635 if ((k = getgroups(ngroups_max, gids)) < 0) {
642 STRV_FOREACH(i, context->supplementary_groups) {
644 if (k >= ngroups_max) {
649 if ((r = get_group_creds(*i, gids+k)) < 0) {
657 if (setgroups(k, gids) < 0) {
668 static int enforce_user(const ExecContext *context, uid_t uid) {
672 /* Sets (but doesn't lookup) the uid and make sure we keep the
673 * capabilities while doing so. */
675 if (context->capabilities) {
677 static const cap_value_t bits[] = {
678 CAP_SETUID, /* Necessary so that we can run setresuid() below */
679 CAP_SETPCAP /* Necessary so that we can set PR_SET_SECUREBITS later on */
682 /* First step: If we need to keep capabilities but
683 * drop privileges we need to make sure we keep our
684 * caps, whiel we drop priviliges. */
686 int sb = context->secure_bits|SECURE_KEEP_CAPS;
688 if (prctl(PR_GET_SECUREBITS) != sb)
689 if (prctl(PR_SET_SECUREBITS, sb) < 0)
693 /* Second step: set the capabilites. This will reduce
694 * the capabilities to the minimum we need. */
696 if (!(d = cap_dup(context->capabilities)))
699 if (cap_set_flag(d, CAP_EFFECTIVE, ELEMENTSOF(bits), bits, CAP_SET) < 0 ||
700 cap_set_flag(d, CAP_PERMITTED, ELEMENTSOF(bits), bits, CAP_SET) < 0) {
706 if (cap_set_proc(d) < 0) {
715 /* Third step: actually set the uids */
716 if (setresuid(uid, uid, uid) < 0)
719 /* At this point we should have all necessary capabilities but
720 are otherwise a normal user. However, the caps might got
721 corrupted due to the setresuid() so we need clean them up
722 later. This is done outside of this call. */
729 static int null_conv(
731 const struct pam_message **msg,
732 struct pam_response **resp,
735 /* We don't support conversations */
740 static int setup_pam(
745 int fds[], unsigned n_fds) {
747 static const struct pam_conv conv = {
752 pam_handle_t *handle = NULL;
754 int pam_code = PAM_SUCCESS;
756 bool close_session = false;
757 pid_t pam_pid = 0, parent_pid;
763 /* We set up PAM in the parent process, then fork. The child
764 * will then stay around untill killed via PR_GET_PDEATHSIG or
765 * systemd via the cgroup logic. It will then remove the PAM
766 * session again. The parent process will exec() the actual
767 * daemon. We do things this way to ensure that the main PID
768 * of the daemon is the one we initially fork()ed. */
770 if ((pam_code = pam_start(name, user, &conv, &handle)) != PAM_SUCCESS) {
776 if ((pam_code = pam_set_item(handle, PAM_TTY, tty)) != PAM_SUCCESS)
779 if ((pam_code = pam_acct_mgmt(handle, PAM_SILENT)) != PAM_SUCCESS)
782 if ((pam_code = pam_open_session(handle, PAM_SILENT)) != PAM_SUCCESS)
785 close_session = true;
787 if ((pam_code = pam_setcred(handle, PAM_ESTABLISH_CRED | PAM_SILENT)) != PAM_SUCCESS)
790 if ((!(e = pam_getenvlist(handle)))) {
791 pam_code = PAM_BUF_ERR;
795 /* Block SIGTERM, so that we know that it won't get lost in
797 if (sigemptyset(&ss) < 0 ||
798 sigaddset(&ss, SIGTERM) < 0 ||
799 sigprocmask(SIG_BLOCK, &ss, &old_ss) < 0)
802 parent_pid = getpid();
804 if ((pam_pid = fork()) < 0)
811 /* The child's job is to reset the PAM session on
814 /* This string must fit in 10 chars (i.e. the length
815 * of "/sbin/init") */
816 rename_process("sd:pam");
818 /* Make sure we don't keep open the passed fds in this
819 child. We assume that otherwise only those fds are
820 open here that have been opened by PAM. */
821 close_many(fds, n_fds);
823 /* Wait until our parent died. This will most likely
824 * not work since the kernel does not allow
825 * unpriviliged paretns kill their priviliged children
826 * this way. We rely on the control groups kill logic
827 * to do the rest for us. */
828 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
831 /* Check if our parent process might already have
833 if (getppid() == parent_pid) {
834 if (sigwait(&ss, &sig) < 0)
837 assert(sig == SIGTERM);
840 /* Only if our parent died we'll end the session */
841 if (getppid() != parent_pid)
842 if ((pam_code = pam_close_session(handle, PAM_DATA_SILENT)) != PAM_SUCCESS)
848 pam_end(handle, pam_code | PAM_DATA_SILENT);
852 /* If the child was forked off successfully it will do all the
853 * cleanups, so forget about the handle here. */
856 /* Unblock SIGSUR1 again in the parent */
857 if (sigprocmask(SIG_SETMASK, &old_ss, NULL) < 0)
860 /* We close the log explicitly here, since the PAM modules
861 * might have opened it, but we don't want this fd around. */
869 pam_code = pam_close_session(handle, PAM_DATA_SILENT);
871 pam_end(handle, pam_code | PAM_DATA_SILENT);
879 kill(pam_pid, SIGTERM);
885 int exec_spawn(ExecCommand *command,
887 const ExecContext *context,
888 int fds[], unsigned n_fds,
890 bool apply_permissions,
893 CGroupBonding *cgroup_bondings,
904 assert(fds || n_fds <= 0);
906 if (context->std_input == EXEC_INPUT_SOCKET ||
907 context->std_output == EXEC_OUTPUT_SOCKET ||
908 context->std_error == EXEC_OUTPUT_SOCKET) {
921 argv = command->argv;
923 if (!(line = exec_command_line(argv)))
926 log_debug("About to execute: %s", line);
930 if ((r = cgroup_bonding_realize_list(cgroup_bondings)))
933 if ((pid = fork()) < 0)
939 const char *username = NULL, *home = NULL;
940 uid_t uid = (uid_t) -1;
941 gid_t gid = (gid_t) -1;
942 char **our_env = NULL, **pam_env = NULL, **final_env = NULL;
944 int saved_stdout = -1, saved_stdin = -1;
945 bool keep_stdout = false, keep_stdin = false;
949 /* This string must fit in 10 chars (i.e. the length
950 * of "/sbin/init") */
951 rename_process("sd:exec");
953 /* We reset exactly these signals, since they are the
954 * only ones we set to SIG_IGN in the main daemon. All
955 * others we leave untouched because we set them to
956 * SIG_DFL or a valid handler initially, both of which
957 * will be demoted to SIG_DFL. */
958 default_signals(SIGNALS_CRASH_HANDLER,
961 if (sigemptyset(&ss) < 0 ||
962 sigprocmask(SIG_SETMASK, &ss, NULL) < 0) {
963 r = EXIT_SIGNAL_MASK;
967 if (!context->no_setsid)
973 if (socket_fd >= 0 && context->tcpwrap_name)
974 if (!socket_tcpwrap(socket_fd, context->tcpwrap_name)) {
982 /* Set up terminal for the question */
983 if ((r = setup_confirm_stdio(context,
984 &saved_stdin, &saved_stdout)))
987 /* Now ask the question. */
988 if (!(line = exec_command_line(argv))) {
993 r = ask(&response, "yns", "Execute %s? [Yes, No, Skip] ", line);
996 if (r < 0 || response == 'n') {
999 } else if (response == 's') {
1004 /* Release terminal for the question */
1005 if ((r = restore_confirm_stdio(context,
1006 &saved_stdin, &saved_stdout,
1007 &keep_stdin, &keep_stdout)))
1012 if (setup_input(context, socket_fd) < 0) {
1018 if (setup_output(context, socket_fd, file_name_from_path(command->path)) < 0) {
1023 if (setup_error(context, socket_fd, file_name_from_path(command->path)) < 0) {
1028 if (cgroup_bondings)
1029 if ((r = cgroup_bonding_install_list(cgroup_bondings, 0)) < 0) {
1034 if (context->oom_adjust_set) {
1037 snprintf(t, sizeof(t), "%i", context->oom_adjust);
1040 if (write_one_line_file("/proc/self/oom_adj", t) < 0) {
1041 r = EXIT_OOM_ADJUST;
1046 if (context->nice_set)
1047 if (setpriority(PRIO_PROCESS, 0, context->nice) < 0) {
1052 if (context->cpu_sched_set) {
1053 struct sched_param param;
1056 param.sched_priority = context->cpu_sched_priority;
1058 if (sched_setscheduler(0, context->cpu_sched_policy |
1059 (context->cpu_sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0), ¶m) < 0) {
1060 r = EXIT_SETSCHEDULER;
1065 if (context->cpu_affinity_set)
1066 if (sched_setaffinity(0, sizeof(context->cpu_affinity), &context->cpu_affinity) < 0) {
1067 r = EXIT_CPUAFFINITY;
1071 if (context->ioprio_set)
1072 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
1077 if (context->timer_slack_ns_set)
1078 if (prctl(PR_SET_TIMERSLACK, context->timer_slack_ns_set) < 0) {
1079 r = EXIT_TIMERSLACK;
1083 if (context->user) {
1084 username = context->user;
1085 if (get_user_creds(&username, &uid, &gid, &home) < 0) {
1090 if (is_terminal_input(context->std_input))
1091 if (chown_terminal(STDIN_FILENO, uid) < 0) {
1098 if (context->pam_name && username) {
1099 /* Make sure no fds leak into the PAM
1100 * supervisor process. We will call this later
1101 * on again to make sure that any fds leaked
1102 * by the PAM modules get closed before our
1104 if (close_all_fds(fds, n_fds) < 0) {
1109 if (setup_pam(context->pam_name, username, context->tty_path, &pam_env, fds, n_fds) < 0) {
1116 if (apply_permissions)
1117 if (enforce_groups(context, username, uid) < 0) {
1122 umask(context->umask);
1124 if (strv_length(context->read_write_dirs) > 0 ||
1125 strv_length(context->read_only_dirs) > 0 ||
1126 strv_length(context->inaccessible_dirs) > 0 ||
1127 context->mount_flags != MS_SHARED ||
1128 context->private_tmp)
1129 if ((r = setup_namespace(
1130 context->read_write_dirs,
1131 context->read_only_dirs,
1132 context->inaccessible_dirs,
1133 context->private_tmp,
1134 context->mount_flags)) < 0)
1138 if (context->root_directory)
1139 if (chroot(context->root_directory) < 0) {
1144 if (chdir(context->working_directory ? context->working_directory : "/") < 0) {
1152 if (asprintf(&d, "%s/%s",
1153 context->root_directory ? context->root_directory : "",
1154 context->working_directory ? context->working_directory : "") < 0) {
1168 if (close_all_fds(fds, n_fds) < 0 ||
1169 shift_fds(fds, n_fds) < 0 ||
1170 flags_fds(fds, n_fds, context->non_blocking) < 0) {
1175 if (apply_permissions) {
1177 for (i = 0; i < RLIMIT_NLIMITS; i++) {
1178 if (!context->rlimit[i])
1181 if (setrlimit(i, context->rlimit[i]) < 0) {
1188 if (enforce_user(context, uid) < 0) {
1193 /* PR_GET_SECUREBITS is not priviliged, while
1194 * PR_SET_SECUREBITS is. So to suppress
1195 * potential EPERMs we'll try not to call
1196 * PR_SET_SECUREBITS unless necessary. */
1197 if (prctl(PR_GET_SECUREBITS) != context->secure_bits)
1198 if (prctl(PR_SET_SECUREBITS, context->secure_bits) < 0) {
1199 r = EXIT_SECUREBITS;
1203 if (context->capabilities)
1204 if (cap_set_proc(context->capabilities) < 0) {
1205 r = EXIT_CAPABILITIES;
1210 if (!(our_env = new0(char*, 6))) {
1216 if (asprintf(our_env + n_env++, "LISTEN_PID=%lu", (unsigned long) getpid()) < 0 ||
1217 asprintf(our_env + n_env++, "LISTEN_FDS=%u", n_fds) < 0) {
1223 if (asprintf(our_env + n_env++, "HOME=%s", home) < 0) {
1229 if (asprintf(our_env + n_env++, "LOGNAME=%s", username) < 0 ||
1230 asprintf(our_env + n_env++, "USER=%s", username) < 0) {
1237 if (!(final_env = strv_env_merge(
1241 context->environment,
1248 execve(command->path, argv, final_env);
1253 strv_free(final_env);
1256 if (saved_stdin >= 0)
1257 close_nointr_nofail(saved_stdin);
1259 if (saved_stdout >= 0)
1260 close_nointr_nofail(saved_stdout);
1265 /* We add the new process to the cgroup both in the child (so
1266 * that we can be sure that no user code is ever executed
1267 * outside of the cgroup) and in the parent (so that we can be
1268 * sure that when we kill the cgroup the process will be
1270 if (cgroup_bondings)
1271 cgroup_bonding_install_list(cgroup_bondings, pid);
1273 log_debug("Forked %s as %lu", command->path, (unsigned long) pid);
1275 command->exec_status.pid = pid;
1276 command->exec_status.start_timestamp = now(CLOCK_REALTIME);
1282 void exec_context_init(ExecContext *c) {
1286 c->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 0);
1287 c->cpu_sched_policy = SCHED_OTHER;
1288 c->syslog_priority = LOG_DAEMON|LOG_INFO;
1289 c->mount_flags = MS_SHARED;
1292 void exec_context_done(ExecContext *c) {
1297 strv_free(c->environment);
1298 c->environment = NULL;
1300 for (l = 0; l < ELEMENTSOF(c->rlimit); l++) {
1302 c->rlimit[l] = NULL;
1305 free(c->working_directory);
1306 c->working_directory = NULL;
1307 free(c->root_directory);
1308 c->root_directory = NULL;
1313 free(c->tcpwrap_name);
1314 c->tcpwrap_name = NULL;
1316 free(c->syslog_identifier);
1317 c->syslog_identifier = NULL;
1325 strv_free(c->supplementary_groups);
1326 c->supplementary_groups = NULL;
1331 if (c->capabilities) {
1332 cap_free(c->capabilities);
1333 c->capabilities = NULL;
1336 strv_free(c->read_only_dirs);
1337 c->read_only_dirs = NULL;
1339 strv_free(c->read_write_dirs);
1340 c->read_write_dirs = NULL;
1342 strv_free(c->inaccessible_dirs);
1343 c->inaccessible_dirs = NULL;
1346 void exec_command_done(ExecCommand *c) {
1356 void exec_command_done_array(ExecCommand *c, unsigned n) {
1359 for (i = 0; i < n; i++)
1360 exec_command_done(c+i);
1363 void exec_command_free_list(ExecCommand *c) {
1367 LIST_REMOVE(ExecCommand, command, c, i);
1368 exec_command_done(i);
1373 void exec_command_free_array(ExecCommand **c, unsigned n) {
1376 for (i = 0; i < n; i++) {
1377 exec_command_free_list(c[i]);
1382 static void strv_fprintf(FILE *f, char **l) {
1388 fprintf(f, " %s", *g);
1391 void exec_context_dump(ExecContext *c, FILE* f, const char *prefix) {
1403 "%sWorkingDirectory: %s\n"
1404 "%sRootDirectory: %s\n"
1405 "%sNonBlocking: %s\n"
1406 "%sPrivateTmp: %s\n",
1408 prefix, c->working_directory ? c->working_directory : "/",
1409 prefix, c->root_directory ? c->root_directory : "/",
1410 prefix, yes_no(c->non_blocking),
1411 prefix, yes_no(c->private_tmp));
1414 for (e = c->environment; *e; e++)
1415 fprintf(f, "%sEnvironment: %s\n", prefix, *e);
1417 if (c->tcpwrap_name)
1419 "%sTCPWrapName: %s\n",
1420 prefix, c->tcpwrap_name);
1427 if (c->oom_adjust_set)
1429 "%sOOMAdjust: %i\n",
1430 prefix, c->oom_adjust);
1432 for (i = 0; i < RLIM_NLIMITS; i++)
1434 fprintf(f, "%s%s: %llu\n", prefix, rlimit_to_string(i), (unsigned long long) c->rlimit[i]->rlim_max);
1438 "%sIOSchedulingClass: %s\n"
1439 "%sIOPriority: %i\n",
1440 prefix, ioprio_class_to_string(IOPRIO_PRIO_CLASS(c->ioprio)),
1441 prefix, (int) IOPRIO_PRIO_DATA(c->ioprio));
1443 if (c->cpu_sched_set)
1445 "%sCPUSchedulingPolicy: %s\n"
1446 "%sCPUSchedulingPriority: %i\n"
1447 "%sCPUSchedulingResetOnFork: %s\n",
1448 prefix, sched_policy_to_string(c->cpu_sched_policy),
1449 prefix, c->cpu_sched_priority,
1450 prefix, yes_no(c->cpu_sched_reset_on_fork));
1452 if (c->cpu_affinity_set) {
1453 fprintf(f, "%sCPUAffinity:", prefix);
1454 for (i = 0; i < CPU_SETSIZE; i++)
1455 if (CPU_ISSET(i, &c->cpu_affinity))
1456 fprintf(f, " %i", i);
1460 if (c->timer_slack_ns_set)
1461 fprintf(f, "%sTimerSlackNS: %lu\n", prefix, c->timer_slack_ns);
1464 "%sStandardInput: %s\n"
1465 "%sStandardOutput: %s\n"
1466 "%sStandardError: %s\n",
1467 prefix, exec_input_to_string(c->std_input),
1468 prefix, exec_output_to_string(c->std_output),
1469 prefix, exec_output_to_string(c->std_error));
1474 prefix, c->tty_path);
1476 if (c->std_output == EXEC_OUTPUT_SYSLOG || c->std_output == EXEC_OUTPUT_KMSG ||
1477 c->std_error == EXEC_OUTPUT_SYSLOG || c->std_error == EXEC_OUTPUT_KMSG)
1479 "%sSyslogFacility: %s\n"
1480 "%sSyslogLevel: %s\n",
1481 prefix, log_facility_to_string(LOG_FAC(c->syslog_priority)),
1482 prefix, log_level_to_string(LOG_PRI(c->syslog_priority)));
1484 if (c->capabilities) {
1486 if ((t = cap_to_text(c->capabilities, NULL))) {
1487 fprintf(f, "%sCapabilities: %s\n",
1494 fprintf(f, "%sSecure Bits:%s%s%s%s%s%s\n",
1496 (c->secure_bits & SECURE_KEEP_CAPS) ? " keep-caps" : "",
1497 (c->secure_bits & SECURE_KEEP_CAPS_LOCKED) ? " keep-caps-locked" : "",
1498 (c->secure_bits & SECURE_NO_SETUID_FIXUP) ? " no-setuid-fixup" : "",
1499 (c->secure_bits & SECURE_NO_SETUID_FIXUP_LOCKED) ? " no-setuid-fixup-locked" : "",
1500 (c->secure_bits & SECURE_NOROOT) ? " noroot" : "",
1501 (c->secure_bits & SECURE_NOROOT_LOCKED) ? "noroot-locked" : "");
1503 if (c->capability_bounding_set_drop) {
1504 fprintf(f, "%sCapabilityBoundingSetDrop:", prefix);
1506 for (i = 0; i <= CAP_LAST_CAP; i++)
1507 if (c->capability_bounding_set_drop & (1 << i)) {
1510 if ((t = cap_to_name(i))) {
1511 fprintf(f, " %s", t);
1520 fprintf(f, "%sUser: %s\n", prefix, c->user);
1522 fprintf(f, "%sGroup: %s\n", prefix, c->group);
1524 if (strv_length(c->supplementary_groups) > 0) {
1525 fprintf(f, "%sSupplementaryGroups:", prefix);
1526 strv_fprintf(f, c->supplementary_groups);
1531 fprintf(f, "%sPAMName: %s\n", prefix, c->pam_name);
1533 if (strv_length(c->read_write_dirs) > 0) {
1534 fprintf(f, "%sReadWriteDirs:", prefix);
1535 strv_fprintf(f, c->read_write_dirs);
1539 if (strv_length(c->read_only_dirs) > 0) {
1540 fprintf(f, "%sReadOnlyDirs:", prefix);
1541 strv_fprintf(f, c->read_only_dirs);
1545 if (strv_length(c->inaccessible_dirs) > 0) {
1546 fprintf(f, "%sInaccessibleDirs:", prefix);
1547 strv_fprintf(f, c->inaccessible_dirs);
1552 void exec_status_fill(ExecStatus *s, pid_t pid, int code, int status) {
1556 s->exit_timestamp = now(CLOCK_REALTIME);
1562 void exec_status_dump(ExecStatus *s, FILE *f, const char *prefix) {
1563 char buf[FORMAT_TIMESTAMP_MAX];
1576 prefix, (unsigned long) s->pid);
1578 if (s->start_timestamp > 0)
1580 "%sStart Timestamp: %s\n",
1581 prefix, format_timestamp(buf, sizeof(buf), s->start_timestamp));
1583 if (s->exit_timestamp > 0)
1585 "%sExit Timestamp: %s\n"
1587 "%sExit Status: %i\n",
1588 prefix, format_timestamp(buf, sizeof(buf), s->exit_timestamp),
1589 prefix, sigchld_code_to_string(s->code),
1593 char *exec_command_line(char **argv) {
1601 STRV_FOREACH(a, argv)
1604 if (!(n = new(char, k)))
1608 STRV_FOREACH(a, argv) {
1615 if (strpbrk(*a, WHITESPACE)) {
1626 /* FIXME: this doesn't really handle arguments that have
1627 * spaces and ticks in them */
1632 void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
1634 const char *prefix2;
1643 p2 = strappend(prefix, "\t");
1644 prefix2 = p2 ? p2 : prefix;
1646 cmd = exec_command_line(c->argv);
1649 "%sCommand Line: %s\n",
1650 prefix, cmd ? cmd : strerror(ENOMEM));
1654 exec_status_dump(&c->exec_status, f, prefix2);
1659 void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
1665 LIST_FOREACH(command, c, c)
1666 exec_command_dump(c, f, prefix);
1669 void exec_command_append_list(ExecCommand **l, ExecCommand *e) {
1676 /* It's kinda important that we keep the order here */
1677 LIST_FIND_TAIL(ExecCommand, command, *l, end);
1678 LIST_INSERT_AFTER(ExecCommand, command, *l, end, e);
1683 int exec_command_set(ExecCommand *c, const char *path, ...) {
1691 l = strv_new_ap(path, ap);
1697 if (!(p = strdup(path))) {
1711 const char* exit_status_to_string(ExitStatus status) {
1713 /* We cast to int here, so that -Wenum doesn't complain that
1714 * EXIT_SUCCESS/EXIT_FAILURE aren't in the enum */
1716 switch ((int) status) {
1724 case EXIT_INVALIDARGUMENT:
1725 return "INVALIDARGUMENT";
1727 case EXIT_NOTIMPLEMENTED:
1728 return "NOTIMPLEMENTED";
1730 case EXIT_NOPERMISSION:
1731 return "NOPERMISSION";
1733 case EXIT_NOTINSTALLED:
1734 return "NOTINSSTALLED";
1736 case EXIT_NOTCONFIGURED:
1737 return "NOTCONFIGURED";
1739 case EXIT_NOTRUNNING:
1740 return "NOTRUNNING";
1760 case EXIT_OOM_ADJUST:
1761 return "OOM_ADJUST";
1763 case EXIT_SIGNAL_MASK:
1764 return "SIGNAL_MASK";
1778 case EXIT_TIMERSLACK:
1779 return "TIMERSLACK";
1781 case EXIT_SECUREBITS:
1782 return "SECUREBITS";
1784 case EXIT_SETSCHEDULER:
1785 return "SETSCHEDULER";
1787 case EXIT_CPUAFFINITY:
1788 return "CPUAFFINITY";
1796 case EXIT_CAPABILITIES:
1797 return "CAPABILITIES";
1822 static const char* const exec_input_table[_EXEC_INPUT_MAX] = {
1823 [EXEC_INPUT_NULL] = "null",
1824 [EXEC_INPUT_TTY] = "tty",
1825 [EXEC_INPUT_TTY_FORCE] = "tty-force",
1826 [EXEC_INPUT_TTY_FAIL] = "tty-fail",
1827 [EXEC_INPUT_SOCKET] = "socket"
1830 static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = {
1831 [EXEC_OUTPUT_INHERIT] = "inherit",
1832 [EXEC_OUTPUT_NULL] = "null",
1833 [EXEC_OUTPUT_TTY] = "tty",
1834 [EXEC_OUTPUT_SYSLOG] = "syslog",
1835 [EXEC_OUTPUT_KMSG] = "kmsg",
1836 [EXEC_OUTPUT_SOCKET] = "socket"
1839 DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput);
1841 DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput);