1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
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"
54 #include "exit-status.h"
56 /* This assumes there is a 'tty' group */
59 static int shift_fds(int fds[], unsigned n_fds) {
60 int start, restart_from;
65 /* Modifies the fds array! (sorts it) */
75 for (i = start; i < (int) n_fds; i++) {
78 /* Already at right index? */
82 if ((nfd = fcntl(fds[i], F_DUPFD, i+3)) < 0)
85 close_nointr_nofail(fds[i]);
88 /* Hmm, the fd we wanted isn't free? Then
89 * let's remember that and try again from here*/
90 if (nfd != i+3 && restart_from < 0)
103 static int flags_fds(const int fds[], unsigned n_fds, bool nonblock) {
112 /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags */
114 for (i = 0; i < n_fds; i++) {
116 if ((r = fd_nonblock(fds[i], nonblock)) < 0)
119 /* We unconditionally drop FD_CLOEXEC from the fds,
120 * since after all we want to pass these fds to our
123 if ((r = fd_cloexec(fds[i], false)) < 0)
130 static const char *tty_path(const ExecContext *context) {
133 if (context->tty_path)
134 return context->tty_path;
136 return "/dev/console";
139 static int open_null_as(int flags, int nfd) {
144 if ((fd = open("/dev/null", flags|O_NOCTTY)) < 0)
148 r = dup2(fd, nfd) < 0 ? -errno : nfd;
149 close_nointr_nofail(fd);
156 static int connect_logger_as(const ExecContext *context, ExecOutput output, const char *ident, int nfd) {
160 struct sockaddr_un un;
164 assert(output < _EXEC_OUTPUT_MAX);
168 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
172 sa.sa.sa_family = AF_UNIX;
173 strncpy(sa.un.sun_path+1, LOGGER_SOCKET, sizeof(sa.un.sun_path)-1);
175 if (connect(fd, &sa.sa, sizeof(sa_family_t) + 1 + sizeof(LOGGER_SOCKET) - 1) < 0) {
176 close_nointr_nofail(fd);
180 if (shutdown(fd, SHUT_RD) < 0) {
181 close_nointr_nofail(fd);
185 /* We speak a very simple protocol between log server
186 * and client: one line for the log destination (kmsg
187 * or syslog), followed by the priority field,
188 * followed by the process name. Since we replaced
189 * stdin/stderr we simple use stdio to write to
190 * it. Note that we use stderr, to minimize buffer
191 * flushing issues. */
198 output == EXEC_OUTPUT_KMSG ? "kmsg" : "syslog",
199 context->syslog_priority,
200 context->syslog_identifier ? context->syslog_identifier : ident,
201 context->syslog_level_prefix);
204 r = dup2(fd, nfd) < 0 ? -errno : nfd;
205 close_nointr_nofail(fd);
211 static int open_terminal_as(const char *path, mode_t mode, int nfd) {
217 if ((fd = open_terminal(path, mode | O_NOCTTY)) < 0)
221 r = dup2(fd, nfd) < 0 ? -errno : nfd;
222 close_nointr_nofail(fd);
229 static bool is_terminal_input(ExecInput i) {
231 i == EXEC_INPUT_TTY ||
232 i == EXEC_INPUT_TTY_FORCE ||
233 i == EXEC_INPUT_TTY_FAIL;
236 static int fixup_input(ExecInput std_input, int socket_fd, bool apply_tty_stdin) {
238 if (is_terminal_input(std_input) && !apply_tty_stdin)
239 return EXEC_INPUT_NULL;
241 if (std_input == EXEC_INPUT_SOCKET && socket_fd < 0)
242 return EXEC_INPUT_NULL;
247 static int fixup_output(ExecOutput std_output, int socket_fd) {
249 if (std_output == EXEC_OUTPUT_SOCKET && socket_fd < 0)
250 return EXEC_OUTPUT_INHERIT;
255 static int setup_input(const ExecContext *context, int socket_fd, bool apply_tty_stdin) {
260 i = fixup_input(context->std_input, socket_fd, apply_tty_stdin);
264 case EXEC_INPUT_NULL:
265 return open_null_as(O_RDONLY, STDIN_FILENO);
268 case EXEC_INPUT_TTY_FORCE:
269 case EXEC_INPUT_TTY_FAIL: {
272 if ((fd = acquire_terminal(
274 i == EXEC_INPUT_TTY_FAIL,
275 i == EXEC_INPUT_TTY_FORCE,
279 if (fd != STDIN_FILENO) {
280 r = dup2(fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
281 close_nointr_nofail(fd);
288 case EXEC_INPUT_SOCKET:
289 return dup2(socket_fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
292 assert_not_reached("Unknown input type");
296 static int setup_output(const ExecContext *context, int socket_fd, const char *ident, bool apply_tty_stdin) {
303 i = fixup_input(context->std_input, socket_fd, apply_tty_stdin);
304 o = fixup_output(context->std_output, socket_fd);
306 /* This expects the input is already set up */
310 case EXEC_OUTPUT_INHERIT:
312 /* If input got downgraded, inherit the original value */
313 if (i == EXEC_INPUT_NULL && is_terminal_input(context->std_input))
314 return open_terminal_as(tty_path(context), O_WRONLY, STDOUT_FILENO);
316 /* If the input is connected to anything that's not a /dev/null, inherit that... */
317 if (i != EXEC_INPUT_NULL)
318 return dup2(STDIN_FILENO, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
320 /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */
322 return STDOUT_FILENO;
324 /* We need to open /dev/null here anew, to get the
325 * right access mode. So we fall through */
327 case EXEC_OUTPUT_NULL:
328 return open_null_as(O_WRONLY, STDOUT_FILENO);
330 case EXEC_OUTPUT_TTY:
331 if (is_terminal_input(i))
332 return dup2(STDIN_FILENO, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
334 /* We don't reset the terminal if this is just about output */
335 return open_terminal_as(tty_path(context), O_WRONLY, STDOUT_FILENO);
337 case EXEC_OUTPUT_SYSLOG:
338 case EXEC_OUTPUT_KMSG:
339 return connect_logger_as(context, o, ident, STDOUT_FILENO);
341 case EXEC_OUTPUT_SOCKET:
342 assert(socket_fd >= 0);
343 return dup2(socket_fd, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
346 assert_not_reached("Unknown output type");
350 static int setup_error(const ExecContext *context, int socket_fd, const char *ident, bool apply_tty_stdin) {
357 i = fixup_input(context->std_input, socket_fd, apply_tty_stdin);
358 o = fixup_output(context->std_output, socket_fd);
359 e = fixup_output(context->std_error, socket_fd);
361 /* This expects the input and output are already set up */
363 /* Don't change the stderr file descriptor if we inherit all
364 * the way and are not on a tty */
365 if (e == EXEC_OUTPUT_INHERIT &&
366 o == EXEC_OUTPUT_INHERIT &&
367 i == EXEC_INPUT_NULL &&
368 !is_terminal_input(context->std_input) &&
370 return STDERR_FILENO;
372 /* Duplicate from stdout if possible */
373 if (e == o || e == EXEC_OUTPUT_INHERIT)
374 return dup2(STDOUT_FILENO, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
378 case EXEC_OUTPUT_NULL:
379 return open_null_as(O_WRONLY, STDERR_FILENO);
381 case EXEC_OUTPUT_TTY:
382 if (is_terminal_input(i))
383 return dup2(STDIN_FILENO, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
385 /* We don't reset the terminal if this is just about output */
386 return open_terminal_as(tty_path(context), O_WRONLY, STDERR_FILENO);
388 case EXEC_OUTPUT_SYSLOG:
389 case EXEC_OUTPUT_KMSG:
390 return connect_logger_as(context, e, ident, STDERR_FILENO);
392 case EXEC_OUTPUT_SOCKET:
393 assert(socket_fd >= 0);
394 return dup2(socket_fd, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
397 assert_not_reached("Unknown error type");
401 static int chown_terminal(int fd, uid_t uid) {
406 /* This might fail. What matters are the results. */
407 (void) fchown(fd, uid, -1);
408 (void) fchmod(fd, TTY_MODE);
410 if (fstat(fd, &st) < 0)
413 if (st.st_uid != uid || (st.st_mode & 0777) != TTY_MODE)
419 static int setup_confirm_stdio(const ExecContext *context,
421 int *_saved_stdout) {
422 int fd = -1, saved_stdin, saved_stdout = -1, r;
425 assert(_saved_stdin);
426 assert(_saved_stdout);
428 /* This returns positive EXIT_xxx return values instead of
429 * negative errno style values! */
431 if ((saved_stdin = fcntl(STDIN_FILENO, F_DUPFD, 3)) < 0)
434 if ((saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD, 3)) < 0) {
439 if ((fd = acquire_terminal(
441 context->std_input == EXEC_INPUT_TTY_FAIL,
442 context->std_input == EXEC_INPUT_TTY_FORCE,
448 if (chown_terminal(fd, getuid()) < 0) {
453 if (dup2(fd, STDIN_FILENO) < 0) {
458 if (dup2(fd, STDOUT_FILENO) < 0) {
464 close_nointr_nofail(fd);
466 *_saved_stdin = saved_stdin;
467 *_saved_stdout = saved_stdout;
472 if (saved_stdout >= 0)
473 close_nointr_nofail(saved_stdout);
475 if (saved_stdin >= 0)
476 close_nointr_nofail(saved_stdin);
479 close_nointr_nofail(fd);
484 static int restore_confirm_stdio(const ExecContext *context,
492 assert(*saved_stdin >= 0);
493 assert(saved_stdout);
494 assert(*saved_stdout >= 0);
496 /* This returns positive EXIT_xxx return values instead of
497 * negative errno style values! */
499 if (is_terminal_input(context->std_input)) {
501 /* The service wants terminal input. */
505 context->std_output == EXEC_OUTPUT_INHERIT ||
506 context->std_output == EXEC_OUTPUT_TTY;
509 /* If the service doesn't want a controlling terminal,
510 * then we need to get rid entirely of what we have
513 if (release_terminal() < 0)
516 if (dup2(*saved_stdin, STDIN_FILENO) < 0)
519 if (dup2(*saved_stdout, STDOUT_FILENO) < 0)
522 *keep_stdout = *keep_stdin = false;
528 static int get_group_creds(const char *groupname, gid_t *gid) {
535 /* We enforce some special rules for gid=0: in order to avoid
536 * NSS lookups for root we hardcode its data. */
538 if (streq(groupname, "root") || streq(groupname, "0")) {
543 if (safe_atolu(groupname, &lu) >= 0) {
545 g = getgrgid((gid_t) lu);
548 g = getgrnam(groupname);
552 return errno != 0 ? -errno : -ESRCH;
558 static int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
568 /* We enforce some special rules for uid=0: in order to avoid
569 * NSS lookups for root we hardcode its data. */
571 if (streq(*username, "root") || streq(*username, "0")) {
579 if (safe_atolu(*username, &lu) >= 0) {
581 p = getpwuid((uid_t) lu);
583 /* If there are multiple users with the same id, make
584 * sure to leave $USER to the configured value instead
585 * of the first occurence in the database. However if
586 * the uid was configured by a numeric uid, then let's
587 * pick the real username from /etc/passwd. */
589 *username = p->pw_name;
592 p = getpwnam(*username);
596 return errno != 0 ? -errno : -ESRCH;
604 static int enforce_groups(const ExecContext *context, const char *username, gid_t gid) {
605 bool keep_groups = false;
610 /* Lookup and ser GID and supplementary group list. Here too
611 * we avoid NSS lookups for gid=0. */
613 if (context->group || username) {
616 if ((r = get_group_creds(context->group, &gid)) < 0)
619 /* First step, initialize groups from /etc/groups */
620 if (username && gid != 0) {
621 if (initgroups(username, gid) < 0)
627 /* Second step, set our gids */
628 if (setresgid(gid, gid, gid) < 0)
632 if (context->supplementary_groups) {
637 /* Final step, initialize any manually set supplementary groups */
638 ngroups_max = (int) sysconf(_SC_NGROUPS_MAX);
640 if (!(gids = new(gid_t, ngroups_max)))
644 if ((k = getgroups(ngroups_max, gids)) < 0) {
651 STRV_FOREACH(i, context->supplementary_groups) {
653 if (k >= ngroups_max) {
658 if ((r = get_group_creds(*i, gids+k)) < 0) {
666 if (setgroups(k, gids) < 0) {
677 static int enforce_user(const ExecContext *context, uid_t uid) {
681 /* Sets (but doesn't lookup) the uid and make sure we keep the
682 * capabilities while doing so. */
684 if (context->capabilities) {
686 static const cap_value_t bits[] = {
687 CAP_SETUID, /* Necessary so that we can run setresuid() below */
688 CAP_SETPCAP /* Necessary so that we can set PR_SET_SECUREBITS later on */
691 /* First step: If we need to keep capabilities but
692 * drop privileges we need to make sure we keep our
693 * caps, whiel we drop priviliges. */
695 int sb = context->secure_bits|SECURE_KEEP_CAPS;
697 if (prctl(PR_GET_SECUREBITS) != sb)
698 if (prctl(PR_SET_SECUREBITS, sb) < 0)
702 /* Second step: set the capabilites. This will reduce
703 * the capabilities to the minimum we need. */
705 if (!(d = cap_dup(context->capabilities)))
708 if (cap_set_flag(d, CAP_EFFECTIVE, ELEMENTSOF(bits), bits, CAP_SET) < 0 ||
709 cap_set_flag(d, CAP_PERMITTED, ELEMENTSOF(bits), bits, CAP_SET) < 0) {
715 if (cap_set_proc(d) < 0) {
724 /* Third step: actually set the uids */
725 if (setresuid(uid, uid, uid) < 0)
728 /* At this point we should have all necessary capabilities but
729 are otherwise a normal user. However, the caps might got
730 corrupted due to the setresuid() so we need clean them up
731 later. This is done outside of this call. */
738 static int null_conv(
740 const struct pam_message **msg,
741 struct pam_response **resp,
744 /* We don't support conversations */
749 static int setup_pam(
754 int fds[], unsigned n_fds) {
756 static const struct pam_conv conv = {
761 pam_handle_t *handle = NULL;
763 int pam_code = PAM_SUCCESS;
765 bool close_session = false;
766 pid_t pam_pid = 0, parent_pid;
772 /* We set up PAM in the parent process, then fork. The child
773 * will then stay around untill killed via PR_GET_PDEATHSIG or
774 * systemd via the cgroup logic. It will then remove the PAM
775 * session again. The parent process will exec() the actual
776 * daemon. We do things this way to ensure that the main PID
777 * of the daemon is the one we initially fork()ed. */
779 if ((pam_code = pam_start(name, user, &conv, &handle)) != PAM_SUCCESS) {
785 if ((pam_code = pam_set_item(handle, PAM_TTY, tty)) != PAM_SUCCESS)
788 if ((pam_code = pam_acct_mgmt(handle, PAM_SILENT)) != PAM_SUCCESS)
791 if ((pam_code = pam_open_session(handle, PAM_SILENT)) != PAM_SUCCESS)
794 close_session = true;
796 if ((pam_code = pam_setcred(handle, PAM_ESTABLISH_CRED | PAM_SILENT)) != PAM_SUCCESS)
799 if ((!(e = pam_getenvlist(handle)))) {
800 pam_code = PAM_BUF_ERR;
804 /* Block SIGTERM, so that we know that it won't get lost in
806 if (sigemptyset(&ss) < 0 ||
807 sigaddset(&ss, SIGTERM) < 0 ||
808 sigprocmask(SIG_BLOCK, &ss, &old_ss) < 0)
811 parent_pid = getpid();
813 if ((pam_pid = fork()) < 0)
820 /* The child's job is to reset the PAM session on
823 /* This string must fit in 10 chars (i.e. the length
824 * of "/sbin/init") */
825 rename_process("sd:pam");
827 /* Make sure we don't keep open the passed fds in this
828 child. We assume that otherwise only those fds are
829 open here that have been opened by PAM. */
830 close_many(fds, n_fds);
832 /* Wait until our parent died. This will most likely
833 * not work since the kernel does not allow
834 * unpriviliged paretns kill their priviliged children
835 * this way. We rely on the control groups kill logic
836 * to do the rest for us. */
837 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
840 /* Check if our parent process might already have
842 if (getppid() == parent_pid) {
843 if (sigwait(&ss, &sig) < 0)
846 assert(sig == SIGTERM);
849 /* Only if our parent died we'll end the session */
850 if (getppid() != parent_pid)
851 if ((pam_code = pam_close_session(handle, PAM_DATA_SILENT)) != PAM_SUCCESS)
857 pam_end(handle, pam_code | PAM_DATA_SILENT);
861 /* If the child was forked off successfully it will do all the
862 * cleanups, so forget about the handle here. */
865 /* Unblock SIGSUR1 again in the parent */
866 if (sigprocmask(SIG_SETMASK, &old_ss, NULL) < 0)
869 /* We close the log explicitly here, since the PAM modules
870 * might have opened it, but we don't want this fd around. */
878 pam_code = pam_close_session(handle, PAM_DATA_SILENT);
880 pam_end(handle, pam_code | PAM_DATA_SILENT);
888 kill(pam_pid, SIGTERM);
894 int exec_spawn(ExecCommand *command,
896 const ExecContext *context,
897 int fds[], unsigned n_fds,
899 bool apply_permissions,
901 bool apply_tty_stdin,
903 CGroupBonding *cgroup_bondings,
914 assert(fds || n_fds <= 0);
916 if (context->std_input == EXEC_INPUT_SOCKET ||
917 context->std_output == EXEC_OUTPUT_SOCKET ||
918 context->std_error == EXEC_OUTPUT_SOCKET) {
931 argv = command->argv;
933 if (!(line = exec_command_line(argv)))
936 log_debug("About to execute: %s", line);
940 if ((r = cgroup_bonding_realize_list(cgroup_bondings)))
943 if ((pid = fork()) < 0)
949 const char *username = NULL, *home = NULL;
950 uid_t uid = (uid_t) -1;
951 gid_t gid = (gid_t) -1;
952 char **our_env = NULL, **pam_env = NULL, **final_env = NULL, **final_argv = NULL;
954 int saved_stdout = -1, saved_stdin = -1;
955 bool keep_stdout = false, keep_stdin = false;
959 /* This string must fit in 10 chars (i.e. the length
960 * of "/sbin/init") */
961 rename_process("sd:exec");
963 /* We reset exactly these signals, since they are the
964 * only ones we set to SIG_IGN in the main daemon. All
965 * others we leave untouched because we set them to
966 * SIG_DFL or a valid handler initially, both of which
967 * will be demoted to SIG_DFL. */
968 default_signals(SIGNALS_CRASH_HANDLER,
971 if (sigemptyset(&ss) < 0 ||
972 sigprocmask(SIG_SETMASK, &ss, NULL) < 0) {
973 r = EXIT_SIGNAL_MASK;
977 /* Close sockets very early to make sure we don't
978 * block init reexecution because it cannot bind its
980 if (close_all_fds(socket_fd >= 0 ? &socket_fd : fds,
981 socket_fd >= 0 ? 1 : n_fds) < 0) {
986 if (!context->same_pgrp)
992 if (context->tcpwrap_name) {
994 if (!socket_tcpwrap(socket_fd, context->tcpwrap_name)) {
999 for (i = 0; i < (int) n_fds; i++) {
1000 if (!socket_tcpwrap(fds[i], context->tcpwrap_name)) {
1007 /* We skip the confirmation step if we shall not apply the TTY */
1008 if (confirm_spawn &&
1009 (!is_terminal_input(context->std_input) || apply_tty_stdin)) {
1012 /* Set up terminal for the question */
1013 if ((r = setup_confirm_stdio(context,
1014 &saved_stdin, &saved_stdout)))
1017 /* Now ask the question. */
1018 if (!(line = exec_command_line(argv))) {
1023 r = ask(&response, "yns", "Execute %s? [Yes, No, Skip] ", line);
1026 if (r < 0 || response == 'n') {
1029 } else if (response == 's') {
1034 /* Release terminal for the question */
1035 if ((r = restore_confirm_stdio(context,
1036 &saved_stdin, &saved_stdout,
1037 &keep_stdin, &keep_stdout)))
1042 if (setup_input(context, socket_fd, apply_tty_stdin) < 0) {
1048 if (setup_output(context, socket_fd, file_name_from_path(command->path), apply_tty_stdin) < 0) {
1053 if (setup_error(context, socket_fd, file_name_from_path(command->path), apply_tty_stdin) < 0) {
1058 if (cgroup_bondings)
1059 if (cgroup_bonding_install_list(cgroup_bondings, 0) < 0) {
1064 if (context->oom_adjust_set) {
1067 snprintf(t, sizeof(t), "%i", context->oom_adjust);
1070 if (write_one_line_file("/proc/self/oom_adj", t) < 0) {
1071 r = EXIT_OOM_ADJUST;
1076 if (context->nice_set)
1077 if (setpriority(PRIO_PROCESS, 0, context->nice) < 0) {
1082 if (context->cpu_sched_set) {
1083 struct sched_param param;
1086 param.sched_priority = context->cpu_sched_priority;
1088 if (sched_setscheduler(0, context->cpu_sched_policy |
1089 (context->cpu_sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0), ¶m) < 0) {
1090 r = EXIT_SETSCHEDULER;
1095 if (context->cpuset)
1096 if (sched_setaffinity(0, CPU_ALLOC_SIZE(context->cpuset_ncpus), context->cpuset) < 0) {
1097 r = EXIT_CPUAFFINITY;
1101 if (context->ioprio_set)
1102 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
1107 if (context->timer_slack_nsec_set)
1108 if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
1109 r = EXIT_TIMERSLACK;
1113 if (context->user) {
1114 username = context->user;
1115 if (get_user_creds(&username, &uid, &gid, &home) < 0) {
1120 if (is_terminal_input(context->std_input))
1121 if (chown_terminal(STDIN_FILENO, uid) < 0) {
1128 if (context->pam_name && username) {
1129 if (setup_pam(context->pam_name, username, context->tty_path, &pam_env, fds, n_fds) < 0) {
1136 if (apply_permissions)
1137 if (enforce_groups(context, username, uid) < 0) {
1142 umask(context->umask);
1144 if (strv_length(context->read_write_dirs) > 0 ||
1145 strv_length(context->read_only_dirs) > 0 ||
1146 strv_length(context->inaccessible_dirs) > 0 ||
1147 context->mount_flags != MS_SHARED ||
1148 context->private_tmp)
1149 if ((r = setup_namespace(
1150 context->read_write_dirs,
1151 context->read_only_dirs,
1152 context->inaccessible_dirs,
1153 context->private_tmp,
1154 context->mount_flags)) < 0)
1158 if (context->root_directory)
1159 if (chroot(context->root_directory) < 0) {
1164 if (chdir(context->working_directory ? context->working_directory : "/") < 0) {
1172 if (asprintf(&d, "%s/%s",
1173 context->root_directory ? context->root_directory : "",
1174 context->working_directory ? context->working_directory : "") < 0) {
1188 /* We repeat the fd closing here, to make sure that
1189 * nothing is leaked from the PAM modules */
1190 if (close_all_fds(fds, n_fds) < 0 ||
1191 shift_fds(fds, n_fds) < 0 ||
1192 flags_fds(fds, n_fds, context->non_blocking) < 0) {
1197 if (apply_permissions) {
1199 for (i = 0; i < RLIMIT_NLIMITS; i++) {
1200 if (!context->rlimit[i])
1203 if (setrlimit(i, context->rlimit[i]) < 0) {
1210 if (enforce_user(context, uid) < 0) {
1215 /* PR_GET_SECUREBITS is not priviliged, while
1216 * PR_SET_SECUREBITS is. So to suppress
1217 * potential EPERMs we'll try not to call
1218 * PR_SET_SECUREBITS unless necessary. */
1219 if (prctl(PR_GET_SECUREBITS) != context->secure_bits)
1220 if (prctl(PR_SET_SECUREBITS, context->secure_bits) < 0) {
1221 r = EXIT_SECUREBITS;
1225 if (context->capabilities)
1226 if (cap_set_proc(context->capabilities) < 0) {
1227 r = EXIT_CAPABILITIES;
1232 if (!(our_env = new0(char*, 6))) {
1238 if (asprintf(our_env + n_env++, "LISTEN_PID=%lu", (unsigned long) getpid()) < 0 ||
1239 asprintf(our_env + n_env++, "LISTEN_FDS=%u", n_fds) < 0) {
1245 if (asprintf(our_env + n_env++, "HOME=%s", home) < 0) {
1251 if (asprintf(our_env + n_env++, "LOGNAME=%s", username) < 0 ||
1252 asprintf(our_env + n_env++, "USER=%s", username) < 0) {
1259 if (!(final_env = strv_env_merge(
1263 context->environment,
1270 if (!(final_argv = replace_env_argv(argv, final_env))) {
1275 execve(command->path, final_argv, final_env);
1280 strv_free(final_env);
1282 strv_free(final_argv);
1284 if (saved_stdin >= 0)
1285 close_nointr_nofail(saved_stdin);
1287 if (saved_stdout >= 0)
1288 close_nointr_nofail(saved_stdout);
1293 /* We add the new process to the cgroup both in the child (so
1294 * that we can be sure that no user code is ever executed
1295 * outside of the cgroup) and in the parent (so that we can be
1296 * sure that when we kill the cgroup the process will be
1298 if (cgroup_bondings)
1299 cgroup_bonding_install_list(cgroup_bondings, pid);
1301 log_debug("Forked %s as %lu", command->path, (unsigned long) pid);
1303 exec_status_start(&command->exec_status, pid);
1309 void exec_context_init(ExecContext *c) {
1313 c->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 0);
1314 c->cpu_sched_policy = SCHED_OTHER;
1315 c->syslog_priority = LOG_DAEMON|LOG_INFO;
1316 c->syslog_level_prefix = true;
1317 c->mount_flags = MS_SHARED;
1318 c->kill_signal = SIGTERM;
1321 void exec_context_done(ExecContext *c) {
1326 strv_free(c->environment);
1327 c->environment = NULL;
1329 for (l = 0; l < ELEMENTSOF(c->rlimit); l++) {
1331 c->rlimit[l] = NULL;
1334 free(c->working_directory);
1335 c->working_directory = NULL;
1336 free(c->root_directory);
1337 c->root_directory = NULL;
1342 free(c->tcpwrap_name);
1343 c->tcpwrap_name = NULL;
1345 free(c->syslog_identifier);
1346 c->syslog_identifier = NULL;
1354 strv_free(c->supplementary_groups);
1355 c->supplementary_groups = NULL;
1360 if (c->capabilities) {
1361 cap_free(c->capabilities);
1362 c->capabilities = NULL;
1365 strv_free(c->read_only_dirs);
1366 c->read_only_dirs = NULL;
1368 strv_free(c->read_write_dirs);
1369 c->read_write_dirs = NULL;
1371 strv_free(c->inaccessible_dirs);
1372 c->inaccessible_dirs = NULL;
1375 CPU_FREE(c->cpuset);
1378 void exec_command_done(ExecCommand *c) {
1388 void exec_command_done_array(ExecCommand *c, unsigned n) {
1391 for (i = 0; i < n; i++)
1392 exec_command_done(c+i);
1395 void exec_command_free_list(ExecCommand *c) {
1399 LIST_REMOVE(ExecCommand, command, c, i);
1400 exec_command_done(i);
1405 void exec_command_free_array(ExecCommand **c, unsigned n) {
1408 for (i = 0; i < n; i++) {
1409 exec_command_free_list(c[i]);
1414 static void strv_fprintf(FILE *f, char **l) {
1420 fprintf(f, " %s", *g);
1423 void exec_context_dump(ExecContext *c, FILE* f, const char *prefix) {
1435 "%sWorkingDirectory: %s\n"
1436 "%sRootDirectory: %s\n"
1437 "%sNonBlocking: %s\n"
1438 "%sPrivateTmp: %s\n",
1440 prefix, c->working_directory ? c->working_directory : "/",
1441 prefix, c->root_directory ? c->root_directory : "/",
1442 prefix, yes_no(c->non_blocking),
1443 prefix, yes_no(c->private_tmp));
1446 for (e = c->environment; *e; e++)
1447 fprintf(f, "%sEnvironment: %s\n", prefix, *e);
1449 if (c->tcpwrap_name)
1451 "%sTCPWrapName: %s\n",
1452 prefix, c->tcpwrap_name);
1459 if (c->oom_adjust_set)
1461 "%sOOMAdjust: %i\n",
1462 prefix, c->oom_adjust);
1464 for (i = 0; i < RLIM_NLIMITS; i++)
1466 fprintf(f, "%s%s: %llu\n", prefix, rlimit_to_string(i), (unsigned long long) c->rlimit[i]->rlim_max);
1470 "%sIOSchedulingClass: %s\n"
1471 "%sIOPriority: %i\n",
1472 prefix, ioprio_class_to_string(IOPRIO_PRIO_CLASS(c->ioprio)),
1473 prefix, (int) IOPRIO_PRIO_DATA(c->ioprio));
1475 if (c->cpu_sched_set)
1477 "%sCPUSchedulingPolicy: %s\n"
1478 "%sCPUSchedulingPriority: %i\n"
1479 "%sCPUSchedulingResetOnFork: %s\n",
1480 prefix, sched_policy_to_string(c->cpu_sched_policy),
1481 prefix, c->cpu_sched_priority,
1482 prefix, yes_no(c->cpu_sched_reset_on_fork));
1485 fprintf(f, "%sCPUAffinity:", prefix);
1486 for (i = 0; i < c->cpuset_ncpus; i++)
1487 if (CPU_ISSET_S(i, CPU_ALLOC_SIZE(c->cpuset_ncpus), c->cpuset))
1488 fprintf(f, " %i", i);
1492 if (c->timer_slack_nsec_set)
1493 fprintf(f, "%sTimerSlackNSec: %lu\n", prefix, c->timer_slack_nsec);
1496 "%sStandardInput: %s\n"
1497 "%sStandardOutput: %s\n"
1498 "%sStandardError: %s\n",
1499 prefix, exec_input_to_string(c->std_input),
1500 prefix, exec_output_to_string(c->std_output),
1501 prefix, exec_output_to_string(c->std_error));
1506 prefix, c->tty_path);
1508 if (c->std_output == EXEC_OUTPUT_SYSLOG || c->std_output == EXEC_OUTPUT_KMSG ||
1509 c->std_error == EXEC_OUTPUT_SYSLOG || c->std_error == EXEC_OUTPUT_KMSG)
1511 "%sSyslogFacility: %s\n"
1512 "%sSyslogLevel: %s\n",
1513 prefix, log_facility_to_string(LOG_FAC(c->syslog_priority)),
1514 prefix, log_level_to_string(LOG_PRI(c->syslog_priority)));
1516 if (c->capabilities) {
1518 if ((t = cap_to_text(c->capabilities, NULL))) {
1519 fprintf(f, "%sCapabilities: %s\n",
1526 fprintf(f, "%sSecure Bits:%s%s%s%s%s%s\n",
1528 (c->secure_bits & SECURE_KEEP_CAPS) ? " keep-caps" : "",
1529 (c->secure_bits & SECURE_KEEP_CAPS_LOCKED) ? " keep-caps-locked" : "",
1530 (c->secure_bits & SECURE_NO_SETUID_FIXUP) ? " no-setuid-fixup" : "",
1531 (c->secure_bits & SECURE_NO_SETUID_FIXUP_LOCKED) ? " no-setuid-fixup-locked" : "",
1532 (c->secure_bits & SECURE_NOROOT) ? " noroot" : "",
1533 (c->secure_bits & SECURE_NOROOT_LOCKED) ? "noroot-locked" : "");
1535 if (c->capability_bounding_set_drop) {
1536 fprintf(f, "%sCapabilityBoundingSetDrop:", prefix);
1538 for (i = 0; i <= CAP_LAST_CAP; i++)
1539 if (c->capability_bounding_set_drop & (1 << i)) {
1542 if ((t = cap_to_name(i))) {
1543 fprintf(f, " %s", t);
1552 fprintf(f, "%sUser: %s\n", prefix, c->user);
1554 fprintf(f, "%sGroup: %s\n", prefix, c->group);
1556 if (strv_length(c->supplementary_groups) > 0) {
1557 fprintf(f, "%sSupplementaryGroups:", prefix);
1558 strv_fprintf(f, c->supplementary_groups);
1563 fprintf(f, "%sPAMName: %s\n", prefix, c->pam_name);
1565 if (strv_length(c->read_write_dirs) > 0) {
1566 fprintf(f, "%sReadWriteDirs:", prefix);
1567 strv_fprintf(f, c->read_write_dirs);
1571 if (strv_length(c->read_only_dirs) > 0) {
1572 fprintf(f, "%sReadOnlyDirs:", prefix);
1573 strv_fprintf(f, c->read_only_dirs);
1577 if (strv_length(c->inaccessible_dirs) > 0) {
1578 fprintf(f, "%sInaccessibleDirs:", prefix);
1579 strv_fprintf(f, c->inaccessible_dirs);
1585 "%sKillSignal: SIG%s\n",
1586 prefix, kill_mode_to_string(c->kill_mode),
1587 prefix, signal_to_string(c->kill_signal));
1590 void exec_status_start(ExecStatus *s, pid_t pid) {
1595 dual_timestamp_get(&s->start_timestamp);
1598 void exec_status_exit(ExecStatus *s, pid_t pid, int code, int status) {
1601 if ((s->pid && s->pid != pid) ||
1602 !s->start_timestamp.realtime <= 0)
1606 dual_timestamp_get(&s->exit_timestamp);
1612 void exec_status_dump(ExecStatus *s, FILE *f, const char *prefix) {
1613 char buf[FORMAT_TIMESTAMP_MAX];
1626 prefix, (unsigned long) s->pid);
1628 if (s->start_timestamp.realtime > 0)
1630 "%sStart Timestamp: %s\n",
1631 prefix, format_timestamp(buf, sizeof(buf), s->start_timestamp.realtime));
1633 if (s->exit_timestamp.realtime > 0)
1635 "%sExit Timestamp: %s\n"
1637 "%sExit Status: %i\n",
1638 prefix, format_timestamp(buf, sizeof(buf), s->exit_timestamp.realtime),
1639 prefix, sigchld_code_to_string(s->code),
1643 char *exec_command_line(char **argv) {
1651 STRV_FOREACH(a, argv)
1654 if (!(n = new(char, k)))
1658 STRV_FOREACH(a, argv) {
1665 if (strpbrk(*a, WHITESPACE)) {
1676 /* FIXME: this doesn't really handle arguments that have
1677 * spaces and ticks in them */
1682 void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
1684 const char *prefix2;
1693 p2 = strappend(prefix, "\t");
1694 prefix2 = p2 ? p2 : prefix;
1696 cmd = exec_command_line(c->argv);
1699 "%sCommand Line: %s\n",
1700 prefix, cmd ? cmd : strerror(ENOMEM));
1704 exec_status_dump(&c->exec_status, f, prefix2);
1709 void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
1715 LIST_FOREACH(command, c, c)
1716 exec_command_dump(c, f, prefix);
1719 void exec_command_append_list(ExecCommand **l, ExecCommand *e) {
1726 /* It's kinda important that we keep the order here */
1727 LIST_FIND_TAIL(ExecCommand, command, *l, end);
1728 LIST_INSERT_AFTER(ExecCommand, command, *l, end, e);
1733 int exec_command_set(ExecCommand *c, const char *path, ...) {
1741 l = strv_new_ap(path, ap);
1747 if (!(p = strdup(path))) {
1761 static const char* const exec_input_table[_EXEC_INPUT_MAX] = {
1762 [EXEC_INPUT_NULL] = "null",
1763 [EXEC_INPUT_TTY] = "tty",
1764 [EXEC_INPUT_TTY_FORCE] = "tty-force",
1765 [EXEC_INPUT_TTY_FAIL] = "tty-fail",
1766 [EXEC_INPUT_SOCKET] = "socket"
1769 static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = {
1770 [EXEC_OUTPUT_INHERIT] = "inherit",
1771 [EXEC_OUTPUT_NULL] = "null",
1772 [EXEC_OUTPUT_TTY] = "tty",
1773 [EXEC_OUTPUT_SYSLOG] = "syslog",
1774 [EXEC_OUTPUT_KMSG] = "kmsg",
1775 [EXEC_OUTPUT_SOCKET] = "socket"
1778 DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput);
1780 DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput);