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>
39 #include <linux/oom.h>
42 #include <security/pam_appl.h>
51 #include "securebits.h"
53 #include "namespace.h"
55 #include "exit-status.h"
58 /* This assumes there is a 'tty' group */
61 static int shift_fds(int fds[], unsigned n_fds) {
62 int start, restart_from;
67 /* Modifies the fds array! (sorts it) */
77 for (i = start; i < (int) n_fds; i++) {
80 /* Already at right index? */
84 if ((nfd = fcntl(fds[i], F_DUPFD, i+3)) < 0)
87 close_nointr_nofail(fds[i]);
90 /* Hmm, the fd we wanted isn't free? Then
91 * let's remember that and try again from here*/
92 if (nfd != i+3 && restart_from < 0)
105 static int flags_fds(const int fds[], unsigned n_fds, bool nonblock) {
114 /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags */
116 for (i = 0; i < n_fds; i++) {
118 if ((r = fd_nonblock(fds[i], nonblock)) < 0)
121 /* We unconditionally drop FD_CLOEXEC from the fds,
122 * since after all we want to pass these fds to our
125 if ((r = fd_cloexec(fds[i], false)) < 0)
132 static const char *tty_path(const ExecContext *context) {
135 if (context->tty_path)
136 return context->tty_path;
138 return "/dev/console";
141 static int open_null_as(int flags, int nfd) {
146 if ((fd = open("/dev/null", flags|O_NOCTTY)) < 0)
150 r = dup2(fd, nfd) < 0 ? -errno : nfd;
151 close_nointr_nofail(fd);
158 static int connect_logger_as(const ExecContext *context, ExecOutput output, const char *ident, int nfd) {
162 struct sockaddr_un un;
166 assert(output < _EXEC_OUTPUT_MAX);
170 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
174 sa.sa.sa_family = AF_UNIX;
175 strncpy(sa.un.sun_path+1, LOGGER_SOCKET, sizeof(sa.un.sun_path)-1);
177 if (connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + 1 + sizeof(LOGGER_SOCKET) - 1) < 0) {
178 close_nointr_nofail(fd);
182 if (shutdown(fd, SHUT_RD) < 0) {
183 close_nointr_nofail(fd);
187 /* We speak a very simple protocol between log server
188 * and client: one line for the log destination (kmsg
189 * or syslog), followed by the priority field,
190 * followed by the process name. Since we replaced
191 * stdin/stderr we simple use stdio to write to
192 * it. Note that we use stderr, to minimize buffer
193 * flushing issues. */
200 output == EXEC_OUTPUT_KMSG ? "kmsg" : "syslog",
201 context->syslog_priority,
202 context->syslog_identifier ? context->syslog_identifier : ident,
203 context->syslog_level_prefix);
206 r = dup2(fd, nfd) < 0 ? -errno : nfd;
207 close_nointr_nofail(fd);
213 static int open_terminal_as(const char *path, mode_t mode, int nfd) {
219 if ((fd = open_terminal(path, mode | O_NOCTTY)) < 0)
223 r = dup2(fd, nfd) < 0 ? -errno : nfd;
224 close_nointr_nofail(fd);
231 static bool is_terminal_input(ExecInput i) {
233 i == EXEC_INPUT_TTY ||
234 i == EXEC_INPUT_TTY_FORCE ||
235 i == EXEC_INPUT_TTY_FAIL;
238 static int fixup_input(ExecInput std_input, int socket_fd, bool apply_tty_stdin) {
240 if (is_terminal_input(std_input) && !apply_tty_stdin)
241 return EXEC_INPUT_NULL;
243 if (std_input == EXEC_INPUT_SOCKET && socket_fd < 0)
244 return EXEC_INPUT_NULL;
249 static int fixup_output(ExecOutput std_output, int socket_fd) {
251 if (std_output == EXEC_OUTPUT_SOCKET && socket_fd < 0)
252 return EXEC_OUTPUT_INHERIT;
257 static int setup_input(const ExecContext *context, int socket_fd, bool apply_tty_stdin) {
262 i = fixup_input(context->std_input, socket_fd, apply_tty_stdin);
266 case EXEC_INPUT_NULL:
267 return open_null_as(O_RDONLY, STDIN_FILENO);
270 case EXEC_INPUT_TTY_FORCE:
271 case EXEC_INPUT_TTY_FAIL: {
274 if ((fd = acquire_terminal(
276 i == EXEC_INPUT_TTY_FAIL,
277 i == EXEC_INPUT_TTY_FORCE,
281 if (fd != STDIN_FILENO) {
282 r = dup2(fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
283 close_nointr_nofail(fd);
290 case EXEC_INPUT_SOCKET:
291 return dup2(socket_fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
294 assert_not_reached("Unknown input type");
298 static int setup_output(const ExecContext *context, int socket_fd, const char *ident, bool apply_tty_stdin) {
305 i = fixup_input(context->std_input, socket_fd, apply_tty_stdin);
306 o = fixup_output(context->std_output, socket_fd);
308 /* This expects the input is already set up */
312 case EXEC_OUTPUT_INHERIT:
314 /* If input got downgraded, inherit the original value */
315 if (i == EXEC_INPUT_NULL && is_terminal_input(context->std_input))
316 return open_terminal_as(tty_path(context), O_WRONLY, STDOUT_FILENO);
318 /* If the input is connected to anything that's not a /dev/null, inherit that... */
319 if (i != EXEC_INPUT_NULL)
320 return dup2(STDIN_FILENO, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
322 /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */
324 return STDOUT_FILENO;
326 /* We need to open /dev/null here anew, to get the
327 * right access mode. So we fall through */
329 case EXEC_OUTPUT_NULL:
330 return open_null_as(O_WRONLY, STDOUT_FILENO);
332 case EXEC_OUTPUT_TTY:
333 if (is_terminal_input(i))
334 return dup2(STDIN_FILENO, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
336 /* We don't reset the terminal if this is just about output */
337 return open_terminal_as(tty_path(context), O_WRONLY, STDOUT_FILENO);
339 case EXEC_OUTPUT_SYSLOG:
340 case EXEC_OUTPUT_KMSG:
341 return connect_logger_as(context, o, ident, STDOUT_FILENO);
343 case EXEC_OUTPUT_SOCKET:
344 assert(socket_fd >= 0);
345 return dup2(socket_fd, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
348 assert_not_reached("Unknown output type");
352 static int setup_error(const ExecContext *context, int socket_fd, const char *ident, bool apply_tty_stdin) {
359 i = fixup_input(context->std_input, socket_fd, apply_tty_stdin);
360 o = fixup_output(context->std_output, socket_fd);
361 e = fixup_output(context->std_error, socket_fd);
363 /* This expects the input and output are already set up */
365 /* Don't change the stderr file descriptor if we inherit all
366 * the way and are not on a tty */
367 if (e == EXEC_OUTPUT_INHERIT &&
368 o == EXEC_OUTPUT_INHERIT &&
369 i == EXEC_INPUT_NULL &&
370 !is_terminal_input(context->std_input) &&
372 return STDERR_FILENO;
374 /* Duplicate from stdout if possible */
375 if (e == o || e == EXEC_OUTPUT_INHERIT)
376 return dup2(STDOUT_FILENO, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
380 case EXEC_OUTPUT_NULL:
381 return open_null_as(O_WRONLY, STDERR_FILENO);
383 case EXEC_OUTPUT_TTY:
384 if (is_terminal_input(i))
385 return dup2(STDIN_FILENO, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
387 /* We don't reset the terminal if this is just about output */
388 return open_terminal_as(tty_path(context), O_WRONLY, STDERR_FILENO);
390 case EXEC_OUTPUT_SYSLOG:
391 case EXEC_OUTPUT_KMSG:
392 return connect_logger_as(context, e, ident, STDERR_FILENO);
394 case EXEC_OUTPUT_SOCKET:
395 assert(socket_fd >= 0);
396 return dup2(socket_fd, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
399 assert_not_reached("Unknown error type");
403 static int chown_terminal(int fd, uid_t uid) {
408 /* This might fail. What matters are the results. */
409 (void) fchown(fd, uid, -1);
410 (void) fchmod(fd, TTY_MODE);
412 if (fstat(fd, &st) < 0)
415 if (st.st_uid != uid || (st.st_mode & 0777) != TTY_MODE)
421 static int setup_confirm_stdio(const ExecContext *context,
423 int *_saved_stdout) {
424 int fd = -1, saved_stdin, saved_stdout = -1, r;
427 assert(_saved_stdin);
428 assert(_saved_stdout);
430 /* This returns positive EXIT_xxx return values instead of
431 * negative errno style values! */
433 if ((saved_stdin = fcntl(STDIN_FILENO, F_DUPFD, 3)) < 0)
436 if ((saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD, 3)) < 0) {
441 if ((fd = acquire_terminal(
443 context->std_input == EXEC_INPUT_TTY_FAIL,
444 context->std_input == EXEC_INPUT_TTY_FORCE,
450 if (chown_terminal(fd, getuid()) < 0) {
455 if (dup2(fd, STDIN_FILENO) < 0) {
460 if (dup2(fd, STDOUT_FILENO) < 0) {
466 close_nointr_nofail(fd);
468 *_saved_stdin = saved_stdin;
469 *_saved_stdout = saved_stdout;
474 if (saved_stdout >= 0)
475 close_nointr_nofail(saved_stdout);
477 if (saved_stdin >= 0)
478 close_nointr_nofail(saved_stdin);
481 close_nointr_nofail(fd);
486 static int restore_confirm_stdio(const ExecContext *context,
494 assert(*saved_stdin >= 0);
495 assert(saved_stdout);
496 assert(*saved_stdout >= 0);
498 /* This returns positive EXIT_xxx return values instead of
499 * negative errno style values! */
501 if (is_terminal_input(context->std_input)) {
503 /* The service wants terminal input. */
507 context->std_output == EXEC_OUTPUT_INHERIT ||
508 context->std_output == EXEC_OUTPUT_TTY;
511 /* If the service doesn't want a controlling terminal,
512 * then we need to get rid entirely of what we have
515 if (release_terminal() < 0)
518 if (dup2(*saved_stdin, STDIN_FILENO) < 0)
521 if (dup2(*saved_stdout, STDOUT_FILENO) < 0)
524 *keep_stdout = *keep_stdin = false;
530 static int get_group_creds(const char *groupname, gid_t *gid) {
537 /* We enforce some special rules for gid=0: in order to avoid
538 * NSS lookups for root we hardcode its data. */
540 if (streq(groupname, "root") || streq(groupname, "0")) {
545 if (safe_atolu(groupname, &lu) >= 0) {
547 g = getgrgid((gid_t) lu);
550 g = getgrnam(groupname);
554 return errno != 0 ? -errno : -ESRCH;
560 static int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
570 /* We enforce some special rules for uid=0: in order to avoid
571 * NSS lookups for root we hardcode its data. */
573 if (streq(*username, "root") || streq(*username, "0")) {
581 if (safe_atolu(*username, &lu) >= 0) {
583 p = getpwuid((uid_t) lu);
585 /* If there are multiple users with the same id, make
586 * sure to leave $USER to the configured value instead
587 * of the first occurence in the database. However if
588 * the uid was configured by a numeric uid, then let's
589 * pick the real username from /etc/passwd. */
591 *username = p->pw_name;
594 p = getpwnam(*username);
598 return errno != 0 ? -errno : -ESRCH;
606 static int enforce_groups(const ExecContext *context, const char *username, gid_t gid) {
607 bool keep_groups = false;
612 /* Lookup and ser GID and supplementary group list. Here too
613 * we avoid NSS lookups for gid=0. */
615 if (context->group || username) {
618 if ((r = get_group_creds(context->group, &gid)) < 0)
621 /* First step, initialize groups from /etc/groups */
622 if (username && gid != 0) {
623 if (initgroups(username, gid) < 0)
629 /* Second step, set our gids */
630 if (setresgid(gid, gid, gid) < 0)
634 if (context->supplementary_groups) {
639 /* Final step, initialize any manually set supplementary groups */
640 ngroups_max = (int) sysconf(_SC_NGROUPS_MAX);
642 if (!(gids = new(gid_t, ngroups_max)))
646 if ((k = getgroups(ngroups_max, gids)) < 0) {
653 STRV_FOREACH(i, context->supplementary_groups) {
655 if (k >= ngroups_max) {
660 if ((r = get_group_creds(*i, gids+k)) < 0) {
668 if (setgroups(k, gids) < 0) {
679 static int enforce_user(const ExecContext *context, uid_t uid) {
683 /* Sets (but doesn't lookup) the uid and make sure we keep the
684 * capabilities while doing so. */
686 if (context->capabilities) {
688 static const cap_value_t bits[] = {
689 CAP_SETUID, /* Necessary so that we can run setresuid() below */
690 CAP_SETPCAP /* Necessary so that we can set PR_SET_SECUREBITS later on */
693 /* First step: If we need to keep capabilities but
694 * drop privileges we need to make sure we keep our
695 * caps, whiel we drop priviliges. */
697 int sb = context->secure_bits|SECURE_KEEP_CAPS;
699 if (prctl(PR_GET_SECUREBITS) != sb)
700 if (prctl(PR_SET_SECUREBITS, sb) < 0)
704 /* Second step: set the capabilites. This will reduce
705 * the capabilities to the minimum we need. */
707 if (!(d = cap_dup(context->capabilities)))
710 if (cap_set_flag(d, CAP_EFFECTIVE, ELEMENTSOF(bits), bits, CAP_SET) < 0 ||
711 cap_set_flag(d, CAP_PERMITTED, ELEMENTSOF(bits), bits, CAP_SET) < 0) {
717 if (cap_set_proc(d) < 0) {
726 /* Third step: actually set the uids */
727 if (setresuid(uid, uid, uid) < 0)
730 /* At this point we should have all necessary capabilities but
731 are otherwise a normal user. However, the caps might got
732 corrupted due to the setresuid() so we need clean them up
733 later. This is done outside of this call. */
740 static int null_conv(
742 const struct pam_message **msg,
743 struct pam_response **resp,
746 /* We don't support conversations */
751 static int setup_pam(
756 int fds[], unsigned n_fds) {
758 static const struct pam_conv conv = {
763 pam_handle_t *handle = NULL;
765 int pam_code = PAM_SUCCESS;
767 bool close_session = false;
768 pid_t pam_pid = 0, parent_pid;
774 /* We set up PAM in the parent process, then fork. The child
775 * will then stay around untill killed via PR_GET_PDEATHSIG or
776 * systemd via the cgroup logic. It will then remove the PAM
777 * session again. The parent process will exec() the actual
778 * daemon. We do things this way to ensure that the main PID
779 * of the daemon is the one we initially fork()ed. */
781 if ((pam_code = pam_start(name, user, &conv, &handle)) != PAM_SUCCESS) {
787 if ((pam_code = pam_set_item(handle, PAM_TTY, tty)) != PAM_SUCCESS)
790 if ((pam_code = pam_acct_mgmt(handle, PAM_SILENT)) != PAM_SUCCESS)
793 if ((pam_code = pam_open_session(handle, PAM_SILENT)) != PAM_SUCCESS)
796 close_session = true;
798 if ((pam_code = pam_setcred(handle, PAM_ESTABLISH_CRED | PAM_SILENT)) != PAM_SUCCESS)
801 if ((!(e = pam_getenvlist(handle)))) {
802 pam_code = PAM_BUF_ERR;
806 /* Block SIGTERM, so that we know that it won't get lost in
808 if (sigemptyset(&ss) < 0 ||
809 sigaddset(&ss, SIGTERM) < 0 ||
810 sigprocmask(SIG_BLOCK, &ss, &old_ss) < 0)
813 parent_pid = getpid();
815 if ((pam_pid = fork()) < 0)
822 /* The child's job is to reset the PAM session on
825 /* This string must fit in 10 chars (i.e. the length
826 * of "/sbin/init") */
827 rename_process("sd:pam");
829 /* Make sure we don't keep open the passed fds in this
830 child. We assume that otherwise only those fds are
831 open here that have been opened by PAM. */
832 close_many(fds, n_fds);
834 /* Wait until our parent died. This will most likely
835 * not work since the kernel does not allow
836 * unpriviliged paretns kill their priviliged children
837 * this way. We rely on the control groups kill logic
838 * to do the rest for us. */
839 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
842 /* Check if our parent process might already have
844 if (getppid() == parent_pid) {
845 if (sigwait(&ss, &sig) < 0)
848 assert(sig == SIGTERM);
851 /* Only if our parent died we'll end the session */
852 if (getppid() != parent_pid)
853 if ((pam_code = pam_close_session(handle, PAM_DATA_SILENT)) != PAM_SUCCESS)
859 pam_end(handle, pam_code | PAM_DATA_SILENT);
863 /* If the child was forked off successfully it will do all the
864 * cleanups, so forget about the handle here. */
867 /* Unblock SIGSUR1 again in the parent */
868 if (sigprocmask(SIG_SETMASK, &old_ss, NULL) < 0)
871 /* We close the log explicitly here, since the PAM modules
872 * might have opened it, but we don't want this fd around. */
880 pam_code = pam_close_session(handle, PAM_DATA_SILENT);
882 pam_end(handle, pam_code | PAM_DATA_SILENT);
890 kill(pam_pid, SIGTERM);
896 int exec_spawn(ExecCommand *command,
898 const ExecContext *context,
899 int fds[], unsigned n_fds,
901 bool apply_permissions,
903 bool apply_tty_stdin,
905 CGroupBonding *cgroup_bondings,
916 assert(fds || n_fds <= 0);
918 if (context->std_input == EXEC_INPUT_SOCKET ||
919 context->std_output == EXEC_OUTPUT_SOCKET ||
920 context->std_error == EXEC_OUTPUT_SOCKET) {
933 argv = command->argv;
935 if (!(line = exec_command_line(argv)))
938 log_debug("About to execute: %s", line);
942 if ((r = cgroup_bonding_realize_list(cgroup_bondings)))
945 if ((pid = fork()) < 0)
951 const char *username = NULL, *home = NULL;
952 uid_t uid = (uid_t) -1;
953 gid_t gid = (gid_t) -1;
954 char **our_env = NULL, **pam_env = NULL, **final_env = NULL, **final_argv = NULL;
956 int saved_stdout = -1, saved_stdin = -1;
957 bool keep_stdout = false, keep_stdin = false;
961 /* This string must fit in 10 chars (i.e. the length
962 * of "/sbin/init") */
963 rename_process("sd:exec");
965 /* We reset exactly these signals, since they are the
966 * only ones we set to SIG_IGN in the main daemon. All
967 * others we leave untouched because we set them to
968 * SIG_DFL or a valid handler initially, both of which
969 * will be demoted to SIG_DFL. */
970 default_signals(SIGNALS_CRASH_HANDLER,
973 if (sigemptyset(&ss) < 0 ||
974 sigprocmask(SIG_SETMASK, &ss, NULL) < 0) {
975 r = EXIT_SIGNAL_MASK;
979 /* Close sockets very early to make sure we don't
980 * block init reexecution because it cannot bind its
982 if (close_all_fds(socket_fd >= 0 ? &socket_fd : fds,
983 socket_fd >= 0 ? 1 : n_fds) < 0) {
988 if (!context->same_pgrp)
994 if (context->tcpwrap_name) {
996 if (!socket_tcpwrap(socket_fd, context->tcpwrap_name)) {
1001 for (i = 0; i < (int) n_fds; i++) {
1002 if (!socket_tcpwrap(fds[i], context->tcpwrap_name)) {
1009 /* We skip the confirmation step if we shall not apply the TTY */
1010 if (confirm_spawn &&
1011 (!is_terminal_input(context->std_input) || apply_tty_stdin)) {
1014 /* Set up terminal for the question */
1015 if ((r = setup_confirm_stdio(context,
1016 &saved_stdin, &saved_stdout)))
1019 /* Now ask the question. */
1020 if (!(line = exec_command_line(argv))) {
1025 r = ask(&response, "yns", "Execute %s? [Yes, No, Skip] ", line);
1028 if (r < 0 || response == 'n') {
1031 } else if (response == 's') {
1036 /* Release terminal for the question */
1037 if ((r = restore_confirm_stdio(context,
1038 &saved_stdin, &saved_stdout,
1039 &keep_stdin, &keep_stdout)))
1043 /* If a socket is connected to STDIN/STDOUT/STDERR, we
1044 * must sure to drop O_NONBLOCK */
1046 fd_nonblock(socket_fd, false);
1049 if (setup_input(context, socket_fd, apply_tty_stdin) < 0) {
1055 if (setup_output(context, socket_fd, file_name_from_path(command->path), apply_tty_stdin) < 0) {
1060 if (setup_error(context, socket_fd, file_name_from_path(command->path), apply_tty_stdin) < 0) {
1065 if (cgroup_bondings)
1066 if (cgroup_bonding_install_list(cgroup_bondings, 0) < 0) {
1071 if (context->oom_score_adjust_set) {
1074 snprintf(t, sizeof(t), "%i", context->oom_score_adjust);
1077 if (write_one_line_file("/proc/self/oom_score_adj", t) < 0) {
1078 /* Compatibility with Linux <= 2.6.35 */
1082 adj = (context->oom_score_adjust * -OOM_DISABLE) / OOM_SCORE_ADJ_MAX;
1083 adj = CLAMP(adj, OOM_DISABLE, OOM_ADJUST_MAX);
1085 snprintf(t, sizeof(t), "%i", adj);
1088 if (write_one_line_file("/proc/self/oom_adj", t) < 0) {
1089 r = EXIT_OOM_ADJUST;
1095 if (context->nice_set)
1096 if (setpriority(PRIO_PROCESS, 0, context->nice) < 0) {
1101 if (context->cpu_sched_set) {
1102 struct sched_param param;
1105 param.sched_priority = context->cpu_sched_priority;
1107 if (sched_setscheduler(0, context->cpu_sched_policy |
1108 (context->cpu_sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0), ¶m) < 0) {
1109 r = EXIT_SETSCHEDULER;
1114 if (context->cpuset)
1115 if (sched_setaffinity(0, CPU_ALLOC_SIZE(context->cpuset_ncpus), context->cpuset) < 0) {
1116 r = EXIT_CPUAFFINITY;
1120 if (context->ioprio_set)
1121 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
1126 if (context->timer_slack_nsec_set)
1127 if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
1128 r = EXIT_TIMERSLACK;
1132 if (context->user) {
1133 username = context->user;
1134 if (get_user_creds(&username, &uid, &gid, &home) < 0) {
1139 if (is_terminal_input(context->std_input))
1140 if (chown_terminal(STDIN_FILENO, uid) < 0) {
1147 if (context->pam_name && username) {
1148 if (setup_pam(context->pam_name, username, context->tty_path, &pam_env, fds, n_fds) < 0) {
1155 if (apply_permissions)
1156 if (enforce_groups(context, username, uid) < 0) {
1161 umask(context->umask);
1163 if (strv_length(context->read_write_dirs) > 0 ||
1164 strv_length(context->read_only_dirs) > 0 ||
1165 strv_length(context->inaccessible_dirs) > 0 ||
1166 context->mount_flags != MS_SHARED ||
1167 context->private_tmp)
1168 if ((r = setup_namespace(
1169 context->read_write_dirs,
1170 context->read_only_dirs,
1171 context->inaccessible_dirs,
1172 context->private_tmp,
1173 context->mount_flags)) < 0)
1177 if (context->root_directory)
1178 if (chroot(context->root_directory) < 0) {
1183 if (chdir(context->working_directory ? context->working_directory : "/") < 0) {
1191 if (asprintf(&d, "%s/%s",
1192 context->root_directory ? context->root_directory : "",
1193 context->working_directory ? context->working_directory : "") < 0) {
1207 /* We repeat the fd closing here, to make sure that
1208 * nothing is leaked from the PAM modules */
1209 if (close_all_fds(fds, n_fds) < 0 ||
1210 shift_fds(fds, n_fds) < 0 ||
1211 flags_fds(fds, n_fds, context->non_blocking) < 0) {
1216 if (apply_permissions) {
1218 for (i = 0; i < RLIMIT_NLIMITS; i++) {
1219 if (!context->rlimit[i])
1222 if (setrlimit(i, context->rlimit[i]) < 0) {
1229 if (enforce_user(context, uid) < 0) {
1234 /* PR_GET_SECUREBITS is not priviliged, while
1235 * PR_SET_SECUREBITS is. So to suppress
1236 * potential EPERMs we'll try not to call
1237 * PR_SET_SECUREBITS unless necessary. */
1238 if (prctl(PR_GET_SECUREBITS) != context->secure_bits)
1239 if (prctl(PR_SET_SECUREBITS, context->secure_bits) < 0) {
1240 r = EXIT_SECUREBITS;
1244 if (context->capabilities)
1245 if (cap_set_proc(context->capabilities) < 0) {
1246 r = EXIT_CAPABILITIES;
1251 if (!(our_env = new0(char*, 6))) {
1257 if (asprintf(our_env + n_env++, "LISTEN_PID=%lu", (unsigned long) getpid()) < 0 ||
1258 asprintf(our_env + n_env++, "LISTEN_FDS=%u", n_fds) < 0) {
1264 if (asprintf(our_env + n_env++, "HOME=%s", home) < 0) {
1270 if (asprintf(our_env + n_env++, "LOGNAME=%s", username) < 0 ||
1271 asprintf(our_env + n_env++, "USER=%s", username) < 0) {
1278 if (!(final_env = strv_env_merge(
1282 context->environment,
1289 if (!(final_argv = replace_env_argv(argv, final_env))) {
1294 execve(command->path, final_argv, final_env);
1299 strv_free(final_env);
1301 strv_free(final_argv);
1303 if (saved_stdin >= 0)
1304 close_nointr_nofail(saved_stdin);
1306 if (saved_stdout >= 0)
1307 close_nointr_nofail(saved_stdout);
1312 /* We add the new process to the cgroup both in the child (so
1313 * that we can be sure that no user code is ever executed
1314 * outside of the cgroup) and in the parent (so that we can be
1315 * sure that when we kill the cgroup the process will be
1317 if (cgroup_bondings)
1318 cgroup_bonding_install_list(cgroup_bondings, pid);
1320 log_debug("Forked %s as %lu", command->path, (unsigned long) pid);
1322 exec_status_start(&command->exec_status, pid);
1328 void exec_context_init(ExecContext *c) {
1332 c->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 0);
1333 c->cpu_sched_policy = SCHED_OTHER;
1334 c->syslog_priority = LOG_DAEMON|LOG_INFO;
1335 c->syslog_level_prefix = true;
1336 c->mount_flags = MS_SHARED;
1337 c->kill_signal = SIGTERM;
1340 void exec_context_done(ExecContext *c) {
1345 strv_free(c->environment);
1346 c->environment = NULL;
1348 for (l = 0; l < ELEMENTSOF(c->rlimit); l++) {
1350 c->rlimit[l] = NULL;
1353 free(c->working_directory);
1354 c->working_directory = NULL;
1355 free(c->root_directory);
1356 c->root_directory = NULL;
1361 free(c->tcpwrap_name);
1362 c->tcpwrap_name = NULL;
1364 free(c->syslog_identifier);
1365 c->syslog_identifier = NULL;
1373 strv_free(c->supplementary_groups);
1374 c->supplementary_groups = NULL;
1379 if (c->capabilities) {
1380 cap_free(c->capabilities);
1381 c->capabilities = NULL;
1384 strv_free(c->read_only_dirs);
1385 c->read_only_dirs = NULL;
1387 strv_free(c->read_write_dirs);
1388 c->read_write_dirs = NULL;
1390 strv_free(c->inaccessible_dirs);
1391 c->inaccessible_dirs = NULL;
1394 CPU_FREE(c->cpuset);
1397 void exec_command_done(ExecCommand *c) {
1407 void exec_command_done_array(ExecCommand *c, unsigned n) {
1410 for (i = 0; i < n; i++)
1411 exec_command_done(c+i);
1414 void exec_command_free_list(ExecCommand *c) {
1418 LIST_REMOVE(ExecCommand, command, c, i);
1419 exec_command_done(i);
1424 void exec_command_free_array(ExecCommand **c, unsigned n) {
1427 for (i = 0; i < n; i++) {
1428 exec_command_free_list(c[i]);
1433 static void strv_fprintf(FILE *f, char **l) {
1439 fprintf(f, " %s", *g);
1442 void exec_context_dump(ExecContext *c, FILE* f, const char *prefix) {
1454 "%sWorkingDirectory: %s\n"
1455 "%sRootDirectory: %s\n"
1456 "%sNonBlocking: %s\n"
1457 "%sPrivateTmp: %s\n",
1459 prefix, c->working_directory ? c->working_directory : "/",
1460 prefix, c->root_directory ? c->root_directory : "/",
1461 prefix, yes_no(c->non_blocking),
1462 prefix, yes_no(c->private_tmp));
1465 for (e = c->environment; *e; e++)
1466 fprintf(f, "%sEnvironment: %s\n", prefix, *e);
1468 if (c->tcpwrap_name)
1470 "%sTCPWrapName: %s\n",
1471 prefix, c->tcpwrap_name);
1478 if (c->oom_score_adjust_set)
1480 "%sOOMScoreAdjust: %i\n",
1481 prefix, c->oom_score_adjust);
1483 for (i = 0; i < RLIM_NLIMITS; i++)
1485 fprintf(f, "%s%s: %llu\n", prefix, rlimit_to_string(i), (unsigned long long) c->rlimit[i]->rlim_max);
1489 "%sIOSchedulingClass: %s\n"
1490 "%sIOPriority: %i\n",
1491 prefix, ioprio_class_to_string(IOPRIO_PRIO_CLASS(c->ioprio)),
1492 prefix, (int) IOPRIO_PRIO_DATA(c->ioprio));
1494 if (c->cpu_sched_set)
1496 "%sCPUSchedulingPolicy: %s\n"
1497 "%sCPUSchedulingPriority: %i\n"
1498 "%sCPUSchedulingResetOnFork: %s\n",
1499 prefix, sched_policy_to_string(c->cpu_sched_policy),
1500 prefix, c->cpu_sched_priority,
1501 prefix, yes_no(c->cpu_sched_reset_on_fork));
1504 fprintf(f, "%sCPUAffinity:", prefix);
1505 for (i = 0; i < c->cpuset_ncpus; i++)
1506 if (CPU_ISSET_S(i, CPU_ALLOC_SIZE(c->cpuset_ncpus), c->cpuset))
1507 fprintf(f, " %i", i);
1511 if (c->timer_slack_nsec_set)
1512 fprintf(f, "%sTimerSlackNSec: %lu\n", prefix, c->timer_slack_nsec);
1515 "%sStandardInput: %s\n"
1516 "%sStandardOutput: %s\n"
1517 "%sStandardError: %s\n",
1518 prefix, exec_input_to_string(c->std_input),
1519 prefix, exec_output_to_string(c->std_output),
1520 prefix, exec_output_to_string(c->std_error));
1525 prefix, c->tty_path);
1527 if (c->std_output == EXEC_OUTPUT_SYSLOG || c->std_output == EXEC_OUTPUT_KMSG ||
1528 c->std_error == EXEC_OUTPUT_SYSLOG || c->std_error == EXEC_OUTPUT_KMSG)
1530 "%sSyslogFacility: %s\n"
1531 "%sSyslogLevel: %s\n",
1532 prefix, log_facility_to_string(LOG_FAC(c->syslog_priority)),
1533 prefix, log_level_to_string(LOG_PRI(c->syslog_priority)));
1535 if (c->capabilities) {
1537 if ((t = cap_to_text(c->capabilities, NULL))) {
1538 fprintf(f, "%sCapabilities: %s\n",
1545 fprintf(f, "%sSecure Bits:%s%s%s%s%s%s\n",
1547 (c->secure_bits & SECURE_KEEP_CAPS) ? " keep-caps" : "",
1548 (c->secure_bits & SECURE_KEEP_CAPS_LOCKED) ? " keep-caps-locked" : "",
1549 (c->secure_bits & SECURE_NO_SETUID_FIXUP) ? " no-setuid-fixup" : "",
1550 (c->secure_bits & SECURE_NO_SETUID_FIXUP_LOCKED) ? " no-setuid-fixup-locked" : "",
1551 (c->secure_bits & SECURE_NOROOT) ? " noroot" : "",
1552 (c->secure_bits & SECURE_NOROOT_LOCKED) ? "noroot-locked" : "");
1554 if (c->capability_bounding_set_drop) {
1555 fprintf(f, "%sCapabilityBoundingSetDrop:", prefix);
1557 for (i = 0; i <= CAP_LAST_CAP; i++)
1558 if (c->capability_bounding_set_drop & (1 << i)) {
1561 if ((t = cap_to_name(i))) {
1562 fprintf(f, " %s", t);
1571 fprintf(f, "%sUser: %s\n", prefix, c->user);
1573 fprintf(f, "%sGroup: %s\n", prefix, c->group);
1575 if (strv_length(c->supplementary_groups) > 0) {
1576 fprintf(f, "%sSupplementaryGroups:", prefix);
1577 strv_fprintf(f, c->supplementary_groups);
1582 fprintf(f, "%sPAMName: %s\n", prefix, c->pam_name);
1584 if (strv_length(c->read_write_dirs) > 0) {
1585 fprintf(f, "%sReadWriteDirs:", prefix);
1586 strv_fprintf(f, c->read_write_dirs);
1590 if (strv_length(c->read_only_dirs) > 0) {
1591 fprintf(f, "%sReadOnlyDirs:", prefix);
1592 strv_fprintf(f, c->read_only_dirs);
1596 if (strv_length(c->inaccessible_dirs) > 0) {
1597 fprintf(f, "%sInaccessibleDirs:", prefix);
1598 strv_fprintf(f, c->inaccessible_dirs);
1604 "%sKillSignal: SIG%s\n",
1605 prefix, kill_mode_to_string(c->kill_mode),
1606 prefix, signal_to_string(c->kill_signal));
1609 void exec_status_start(ExecStatus *s, pid_t pid) {
1614 dual_timestamp_get(&s->start_timestamp);
1617 void exec_status_exit(ExecStatus *s, pid_t pid, int code, int status) {
1620 if ((s->pid && s->pid != pid) ||
1621 !s->start_timestamp.realtime <= 0)
1625 dual_timestamp_get(&s->exit_timestamp);
1631 void exec_status_dump(ExecStatus *s, FILE *f, const char *prefix) {
1632 char buf[FORMAT_TIMESTAMP_MAX];
1645 prefix, (unsigned long) s->pid);
1647 if (s->start_timestamp.realtime > 0)
1649 "%sStart Timestamp: %s\n",
1650 prefix, format_timestamp(buf, sizeof(buf), s->start_timestamp.realtime));
1652 if (s->exit_timestamp.realtime > 0)
1654 "%sExit Timestamp: %s\n"
1656 "%sExit Status: %i\n",
1657 prefix, format_timestamp(buf, sizeof(buf), s->exit_timestamp.realtime),
1658 prefix, sigchld_code_to_string(s->code),
1662 char *exec_command_line(char **argv) {
1670 STRV_FOREACH(a, argv)
1673 if (!(n = new(char, k)))
1677 STRV_FOREACH(a, argv) {
1684 if (strpbrk(*a, WHITESPACE)) {
1695 /* FIXME: this doesn't really handle arguments that have
1696 * spaces and ticks in them */
1701 void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
1703 const char *prefix2;
1712 p2 = strappend(prefix, "\t");
1713 prefix2 = p2 ? p2 : prefix;
1715 cmd = exec_command_line(c->argv);
1718 "%sCommand Line: %s\n",
1719 prefix, cmd ? cmd : strerror(ENOMEM));
1723 exec_status_dump(&c->exec_status, f, prefix2);
1728 void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
1734 LIST_FOREACH(command, c, c)
1735 exec_command_dump(c, f, prefix);
1738 void exec_command_append_list(ExecCommand **l, ExecCommand *e) {
1745 /* It's kinda important that we keep the order here */
1746 LIST_FIND_TAIL(ExecCommand, command, *l, end);
1747 LIST_INSERT_AFTER(ExecCommand, command, *l, end, e);
1752 int exec_command_set(ExecCommand *c, const char *path, ...) {
1760 l = strv_new_ap(path, ap);
1766 if (!(p = strdup(path))) {
1780 static const char* const exec_input_table[_EXEC_INPUT_MAX] = {
1781 [EXEC_INPUT_NULL] = "null",
1782 [EXEC_INPUT_TTY] = "tty",
1783 [EXEC_INPUT_TTY_FORCE] = "tty-force",
1784 [EXEC_INPUT_TTY_FAIL] = "tty-fail",
1785 [EXEC_INPUT_SOCKET] = "socket"
1788 static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = {
1789 [EXEC_OUTPUT_INHERIT] = "inherit",
1790 [EXEC_OUTPUT_NULL] = "null",
1791 [EXEC_OUTPUT_TTY] = "tty",
1792 [EXEC_OUTPUT_SYSLOG] = "syslog",
1793 [EXEC_OUTPUT_KMSG] = "kmsg",
1794 [EXEC_OUTPUT_SOCKET] = "socket"
1797 DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput);
1799 DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput);