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"
57 #include "utmp-wtmp.h"
59 /* This assumes there is a 'tty' group */
62 static int shift_fds(int fds[], unsigned n_fds) {
63 int start, restart_from;
68 /* Modifies the fds array! (sorts it) */
78 for (i = start; i < (int) n_fds; i++) {
81 /* Already at right index? */
85 if ((nfd = fcntl(fds[i], F_DUPFD, i+3)) < 0)
88 close_nointr_nofail(fds[i]);
91 /* Hmm, the fd we wanted isn't free? Then
92 * let's remember that and try again from here*/
93 if (nfd != i+3 && restart_from < 0)
100 start = restart_from;
106 static int flags_fds(const int fds[], unsigned n_fds, bool nonblock) {
115 /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags */
117 for (i = 0; i < n_fds; i++) {
119 if ((r = fd_nonblock(fds[i], nonblock)) < 0)
122 /* We unconditionally drop FD_CLOEXEC from the fds,
123 * since after all we want to pass these fds to our
126 if ((r = fd_cloexec(fds[i], false)) < 0)
133 static const char *tty_path(const ExecContext *context) {
136 if (context->tty_path)
137 return context->tty_path;
139 return "/dev/console";
142 static int open_null_as(int flags, int nfd) {
147 if ((fd = open("/dev/null", flags|O_NOCTTY)) < 0)
151 r = dup2(fd, nfd) < 0 ? -errno : nfd;
152 close_nointr_nofail(fd);
159 static int connect_logger_as(const ExecContext *context, ExecOutput output, const char *ident, int nfd) {
163 struct sockaddr_un un;
167 assert(output < _EXEC_OUTPUT_MAX);
171 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
175 sa.sa.sa_family = AF_UNIX;
176 strncpy(sa.un.sun_path+1, LOGGER_SOCKET, sizeof(sa.un.sun_path)-1);
178 if (connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + 1 + sizeof(LOGGER_SOCKET) - 1) < 0) {
179 close_nointr_nofail(fd);
183 if (shutdown(fd, SHUT_RD) < 0) {
184 close_nointr_nofail(fd);
188 /* We speak a very simple protocol between log server
189 * and client: one line for the log destination (kmsg
190 * or syslog), followed by the priority field,
191 * followed by the process name. Since we replaced
192 * stdin/stderr we simple use stdio to write to
193 * it. Note that we use stderr, to minimize buffer
194 * flushing issues. */
201 output == EXEC_OUTPUT_KMSG ? "kmsg" : "syslog",
202 context->syslog_priority,
203 context->syslog_identifier ? context->syslog_identifier : ident,
204 context->syslog_level_prefix);
207 r = dup2(fd, nfd) < 0 ? -errno : nfd;
208 close_nointr_nofail(fd);
214 static int open_terminal_as(const char *path, mode_t mode, int nfd) {
220 if ((fd = open_terminal(path, mode | O_NOCTTY)) < 0)
224 r = dup2(fd, nfd) < 0 ? -errno : nfd;
225 close_nointr_nofail(fd);
232 static bool is_terminal_input(ExecInput i) {
234 i == EXEC_INPUT_TTY ||
235 i == EXEC_INPUT_TTY_FORCE ||
236 i == EXEC_INPUT_TTY_FAIL;
239 static int fixup_input(ExecInput std_input, int socket_fd, bool apply_tty_stdin) {
241 if (is_terminal_input(std_input) && !apply_tty_stdin)
242 return EXEC_INPUT_NULL;
244 if (std_input == EXEC_INPUT_SOCKET && socket_fd < 0)
245 return EXEC_INPUT_NULL;
250 static int fixup_output(ExecOutput std_output, int socket_fd) {
252 if (std_output == EXEC_OUTPUT_SOCKET && socket_fd < 0)
253 return EXEC_OUTPUT_INHERIT;
258 static int setup_input(const ExecContext *context, int socket_fd, bool apply_tty_stdin) {
263 i = fixup_input(context->std_input, socket_fd, apply_tty_stdin);
267 case EXEC_INPUT_NULL:
268 return open_null_as(O_RDONLY, STDIN_FILENO);
271 case EXEC_INPUT_TTY_FORCE:
272 case EXEC_INPUT_TTY_FAIL: {
275 if ((fd = acquire_terminal(
277 i == EXEC_INPUT_TTY_FAIL,
278 i == EXEC_INPUT_TTY_FORCE,
282 if (fd != STDIN_FILENO) {
283 r = dup2(fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
284 close_nointr_nofail(fd);
291 case EXEC_INPUT_SOCKET:
292 return dup2(socket_fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
295 assert_not_reached("Unknown input type");
299 static int setup_output(const ExecContext *context, int socket_fd, const char *ident, bool apply_tty_stdin) {
306 i = fixup_input(context->std_input, socket_fd, apply_tty_stdin);
307 o = fixup_output(context->std_output, socket_fd);
309 /* This expects the input is already set up */
313 case EXEC_OUTPUT_INHERIT:
315 /* If input got downgraded, inherit the original value */
316 if (i == EXEC_INPUT_NULL && is_terminal_input(context->std_input))
317 return open_terminal_as(tty_path(context), O_WRONLY, STDOUT_FILENO);
319 /* If the input is connected to anything that's not a /dev/null, inherit that... */
320 if (i != EXEC_INPUT_NULL)
321 return dup2(STDIN_FILENO, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
323 /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */
325 return STDOUT_FILENO;
327 /* We need to open /dev/null here anew, to get the
328 * right access mode. So we fall through */
330 case EXEC_OUTPUT_NULL:
331 return open_null_as(O_WRONLY, STDOUT_FILENO);
333 case EXEC_OUTPUT_TTY:
334 if (is_terminal_input(i))
335 return dup2(STDIN_FILENO, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
337 /* We don't reset the terminal if this is just about output */
338 return open_terminal_as(tty_path(context), O_WRONLY, STDOUT_FILENO);
340 case EXEC_OUTPUT_SYSLOG:
341 case EXEC_OUTPUT_KMSG:
342 return connect_logger_as(context, o, ident, STDOUT_FILENO);
344 case EXEC_OUTPUT_SOCKET:
345 assert(socket_fd >= 0);
346 return dup2(socket_fd, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
349 assert_not_reached("Unknown output type");
353 static int setup_error(const ExecContext *context, int socket_fd, const char *ident, bool apply_tty_stdin) {
360 i = fixup_input(context->std_input, socket_fd, apply_tty_stdin);
361 o = fixup_output(context->std_output, socket_fd);
362 e = fixup_output(context->std_error, socket_fd);
364 /* This expects the input and output are already set up */
366 /* Don't change the stderr file descriptor if we inherit all
367 * the way and are not on a tty */
368 if (e == EXEC_OUTPUT_INHERIT &&
369 o == EXEC_OUTPUT_INHERIT &&
370 i == EXEC_INPUT_NULL &&
371 !is_terminal_input(context->std_input) &&
373 return STDERR_FILENO;
375 /* Duplicate from stdout if possible */
376 if (e == o || e == EXEC_OUTPUT_INHERIT)
377 return dup2(STDOUT_FILENO, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
381 case EXEC_OUTPUT_NULL:
382 return open_null_as(O_WRONLY, STDERR_FILENO);
384 case EXEC_OUTPUT_TTY:
385 if (is_terminal_input(i))
386 return dup2(STDIN_FILENO, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
388 /* We don't reset the terminal if this is just about output */
389 return open_terminal_as(tty_path(context), O_WRONLY, STDERR_FILENO);
391 case EXEC_OUTPUT_SYSLOG:
392 case EXEC_OUTPUT_KMSG:
393 return connect_logger_as(context, e, ident, STDERR_FILENO);
395 case EXEC_OUTPUT_SOCKET:
396 assert(socket_fd >= 0);
397 return dup2(socket_fd, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
400 assert_not_reached("Unknown error type");
404 static int chown_terminal(int fd, uid_t uid) {
409 /* This might fail. What matters are the results. */
410 (void) fchown(fd, uid, -1);
411 (void) fchmod(fd, TTY_MODE);
413 if (fstat(fd, &st) < 0)
416 if (st.st_uid != uid || (st.st_mode & 0777) != TTY_MODE)
422 static int setup_confirm_stdio(const ExecContext *context,
424 int *_saved_stdout) {
425 int fd = -1, saved_stdin, saved_stdout = -1, r;
428 assert(_saved_stdin);
429 assert(_saved_stdout);
431 /* This returns positive EXIT_xxx return values instead of
432 * negative errno style values! */
434 if ((saved_stdin = fcntl(STDIN_FILENO, F_DUPFD, 3)) < 0)
437 if ((saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD, 3)) < 0) {
442 if ((fd = acquire_terminal(
444 context->std_input == EXEC_INPUT_TTY_FAIL,
445 context->std_input == EXEC_INPUT_TTY_FORCE,
451 if (chown_terminal(fd, getuid()) < 0) {
456 if (dup2(fd, STDIN_FILENO) < 0) {
461 if (dup2(fd, STDOUT_FILENO) < 0) {
467 close_nointr_nofail(fd);
469 *_saved_stdin = saved_stdin;
470 *_saved_stdout = saved_stdout;
475 if (saved_stdout >= 0)
476 close_nointr_nofail(saved_stdout);
478 if (saved_stdin >= 0)
479 close_nointr_nofail(saved_stdin);
482 close_nointr_nofail(fd);
487 static int restore_confirm_stdio(const ExecContext *context,
495 assert(*saved_stdin >= 0);
496 assert(saved_stdout);
497 assert(*saved_stdout >= 0);
499 /* This returns positive EXIT_xxx return values instead of
500 * negative errno style values! */
502 if (is_terminal_input(context->std_input)) {
504 /* The service wants terminal input. */
508 context->std_output == EXEC_OUTPUT_INHERIT ||
509 context->std_output == EXEC_OUTPUT_TTY;
512 /* If the service doesn't want a controlling terminal,
513 * then we need to get rid entirely of what we have
516 if (release_terminal() < 0)
519 if (dup2(*saved_stdin, STDIN_FILENO) < 0)
522 if (dup2(*saved_stdout, STDOUT_FILENO) < 0)
525 *keep_stdout = *keep_stdin = false;
531 static int get_group_creds(const char *groupname, gid_t *gid) {
538 /* We enforce some special rules for gid=0: in order to avoid
539 * NSS lookups for root we hardcode its data. */
541 if (streq(groupname, "root") || streq(groupname, "0")) {
546 if (safe_atolu(groupname, &lu) >= 0) {
548 g = getgrgid((gid_t) lu);
551 g = getgrnam(groupname);
555 return errno != 0 ? -errno : -ESRCH;
561 static int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
571 /* We enforce some special rules for uid=0: in order to avoid
572 * NSS lookups for root we hardcode its data. */
574 if (streq(*username, "root") || streq(*username, "0")) {
582 if (safe_atolu(*username, &lu) >= 0) {
584 p = getpwuid((uid_t) lu);
586 /* If there are multiple users with the same id, make
587 * sure to leave $USER to the configured value instead
588 * of the first occurence in the database. However if
589 * the uid was configured by a numeric uid, then let's
590 * pick the real username from /etc/passwd. */
592 *username = p->pw_name;
595 p = getpwnam(*username);
599 return errno != 0 ? -errno : -ESRCH;
607 static int enforce_groups(const ExecContext *context, const char *username, gid_t gid) {
608 bool keep_groups = false;
613 /* Lookup and ser GID and supplementary group list. Here too
614 * we avoid NSS lookups for gid=0. */
616 if (context->group || username) {
619 if ((r = get_group_creds(context->group, &gid)) < 0)
622 /* First step, initialize groups from /etc/groups */
623 if (username && gid != 0) {
624 if (initgroups(username, gid) < 0)
630 /* Second step, set our gids */
631 if (setresgid(gid, gid, gid) < 0)
635 if (context->supplementary_groups) {
640 /* Final step, initialize any manually set supplementary groups */
641 ngroups_max = (int) sysconf(_SC_NGROUPS_MAX);
643 if (!(gids = new(gid_t, ngroups_max)))
647 if ((k = getgroups(ngroups_max, gids)) < 0) {
654 STRV_FOREACH(i, context->supplementary_groups) {
656 if (k >= ngroups_max) {
661 if ((r = get_group_creds(*i, gids+k)) < 0) {
669 if (setgroups(k, gids) < 0) {
680 static int enforce_user(const ExecContext *context, uid_t uid) {
684 /* Sets (but doesn't lookup) the uid and make sure we keep the
685 * capabilities while doing so. */
687 if (context->capabilities) {
689 static const cap_value_t bits[] = {
690 CAP_SETUID, /* Necessary so that we can run setresuid() below */
691 CAP_SETPCAP /* Necessary so that we can set PR_SET_SECUREBITS later on */
694 /* First step: If we need to keep capabilities but
695 * drop privileges we need to make sure we keep our
696 * caps, whiel we drop priviliges. */
698 int sb = context->secure_bits|SECURE_KEEP_CAPS;
700 if (prctl(PR_GET_SECUREBITS) != sb)
701 if (prctl(PR_SET_SECUREBITS, sb) < 0)
705 /* Second step: set the capabilites. This will reduce
706 * the capabilities to the minimum we need. */
708 if (!(d = cap_dup(context->capabilities)))
711 if (cap_set_flag(d, CAP_EFFECTIVE, ELEMENTSOF(bits), bits, CAP_SET) < 0 ||
712 cap_set_flag(d, CAP_PERMITTED, ELEMENTSOF(bits), bits, CAP_SET) < 0) {
718 if (cap_set_proc(d) < 0) {
727 /* Third step: actually set the uids */
728 if (setresuid(uid, uid, uid) < 0)
731 /* At this point we should have all necessary capabilities but
732 are otherwise a normal user. However, the caps might got
733 corrupted due to the setresuid() so we need clean them up
734 later. This is done outside of this call. */
741 static int null_conv(
743 const struct pam_message **msg,
744 struct pam_response **resp,
747 /* We don't support conversations */
752 static int setup_pam(
757 int fds[], unsigned n_fds) {
759 static const struct pam_conv conv = {
764 pam_handle_t *handle = NULL;
766 int pam_code = PAM_SUCCESS;
768 bool close_session = false;
769 pid_t pam_pid = 0, parent_pid;
775 /* We set up PAM in the parent process, then fork. The child
776 * will then stay around untill killed via PR_GET_PDEATHSIG or
777 * systemd via the cgroup logic. It will then remove the PAM
778 * session again. The parent process will exec() the actual
779 * daemon. We do things this way to ensure that the main PID
780 * of the daemon is the one we initially fork()ed. */
782 if ((pam_code = pam_start(name, user, &conv, &handle)) != PAM_SUCCESS) {
788 if ((pam_code = pam_set_item(handle, PAM_TTY, tty)) != PAM_SUCCESS)
791 if ((pam_code = pam_acct_mgmt(handle, PAM_SILENT)) != PAM_SUCCESS)
794 if ((pam_code = pam_open_session(handle, PAM_SILENT)) != PAM_SUCCESS)
797 close_session = true;
799 if ((pam_code = pam_setcred(handle, PAM_ESTABLISH_CRED | PAM_SILENT)) != PAM_SUCCESS)
802 if ((!(e = pam_getenvlist(handle)))) {
803 pam_code = PAM_BUF_ERR;
807 /* Block SIGTERM, so that we know that it won't get lost in
809 if (sigemptyset(&ss) < 0 ||
810 sigaddset(&ss, SIGTERM) < 0 ||
811 sigprocmask(SIG_BLOCK, &ss, &old_ss) < 0)
814 parent_pid = getpid();
816 if ((pam_pid = fork()) < 0)
823 /* The child's job is to reset the PAM session on
826 /* This string must fit in 10 chars (i.e. the length
827 * of "/sbin/init") */
828 rename_process("sd:pam");
830 /* Make sure we don't keep open the passed fds in this
831 child. We assume that otherwise only those fds are
832 open here that have been opened by PAM. */
833 close_many(fds, n_fds);
835 /* Wait until our parent died. This will most likely
836 * not work since the kernel does not allow
837 * unpriviliged paretns kill their priviliged children
838 * this way. We rely on the control groups kill logic
839 * to do the rest for us. */
840 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
843 /* Check if our parent process might already have
845 if (getppid() == parent_pid) {
846 if (sigwait(&ss, &sig) < 0)
849 assert(sig == SIGTERM);
852 /* Only if our parent died we'll end the session */
853 if (getppid() != parent_pid)
854 if ((pam_code = pam_close_session(handle, PAM_DATA_SILENT)) != PAM_SUCCESS)
860 pam_end(handle, pam_code | PAM_DATA_SILENT);
864 /* If the child was forked off successfully it will do all the
865 * cleanups, so forget about the handle here. */
868 /* Unblock SIGSUR1 again in the parent */
869 if (sigprocmask(SIG_SETMASK, &old_ss, NULL) < 0)
872 /* We close the log explicitly here, since the PAM modules
873 * might have opened it, but we don't want this fd around. */
881 pam_code = pam_close_session(handle, PAM_DATA_SILENT);
883 pam_end(handle, pam_code | PAM_DATA_SILENT);
891 kill(pam_pid, SIGTERM);
897 int exec_spawn(ExecCommand *command,
899 const ExecContext *context,
900 int fds[], unsigned n_fds,
902 bool apply_permissions,
904 bool apply_tty_stdin,
906 CGroupBonding *cgroup_bondings,
917 assert(fds || n_fds <= 0);
919 if (context->std_input == EXEC_INPUT_SOCKET ||
920 context->std_output == EXEC_OUTPUT_SOCKET ||
921 context->std_error == EXEC_OUTPUT_SOCKET) {
934 argv = command->argv;
936 if (!(line = exec_command_line(argv)))
939 log_debug("About to execute: %s", line);
943 if ((r = cgroup_bonding_realize_list(cgroup_bondings)))
946 if ((pid = fork()) < 0)
952 const char *username = NULL, *home = NULL;
953 uid_t uid = (uid_t) -1;
954 gid_t gid = (gid_t) -1;
955 char **our_env = NULL, **pam_env = NULL, **final_env = NULL, **final_argv = NULL;
957 int saved_stdout = -1, saved_stdin = -1;
958 bool keep_stdout = false, keep_stdin = false;
962 /* This string must fit in 10 chars (i.e. the length
963 * of "/sbin/init") */
964 rename_process("sd:exec");
966 /* We reset exactly these signals, since they are the
967 * only ones we set to SIG_IGN in the main daemon. All
968 * others we leave untouched because we set them to
969 * SIG_DFL or a valid handler initially, both of which
970 * will be demoted to SIG_DFL. */
971 default_signals(SIGNALS_CRASH_HANDLER,
974 if (sigemptyset(&ss) < 0 ||
975 sigprocmask(SIG_SETMASK, &ss, NULL) < 0) {
976 r = EXIT_SIGNAL_MASK;
980 /* Close sockets very early to make sure we don't
981 * block init reexecution because it cannot bind its
983 if (close_all_fds(socket_fd >= 0 ? &socket_fd : fds,
984 socket_fd >= 0 ? 1 : n_fds) < 0) {
989 if (!context->same_pgrp)
995 if (context->tcpwrap_name) {
997 if (!socket_tcpwrap(socket_fd, context->tcpwrap_name)) {
1002 for (i = 0; i < (int) n_fds; i++) {
1003 if (!socket_tcpwrap(fds[i], context->tcpwrap_name)) {
1010 /* We skip the confirmation step if we shall not apply the TTY */
1011 if (confirm_spawn &&
1012 (!is_terminal_input(context->std_input) || apply_tty_stdin)) {
1015 /* Set up terminal for the question */
1016 if ((r = setup_confirm_stdio(context,
1017 &saved_stdin, &saved_stdout)))
1020 /* Now ask the question. */
1021 if (!(line = exec_command_line(argv))) {
1026 r = ask(&response, "yns", "Execute %s? [Yes, No, Skip] ", line);
1029 if (r < 0 || response == 'n') {
1032 } else if (response == 's') {
1037 /* Release terminal for the question */
1038 if ((r = restore_confirm_stdio(context,
1039 &saved_stdin, &saved_stdout,
1040 &keep_stdin, &keep_stdout)))
1044 /* If a socket is connected to STDIN/STDOUT/STDERR, we
1045 * must sure to drop O_NONBLOCK */
1047 fd_nonblock(socket_fd, false);
1050 if (setup_input(context, socket_fd, apply_tty_stdin) < 0) {
1056 if (setup_output(context, socket_fd, file_name_from_path(command->path), apply_tty_stdin) < 0) {
1061 if (setup_error(context, socket_fd, file_name_from_path(command->path), apply_tty_stdin) < 0) {
1066 if (cgroup_bondings)
1067 if (cgroup_bonding_install_list(cgroup_bondings, 0) < 0) {
1072 if (context->oom_score_adjust_set) {
1075 snprintf(t, sizeof(t), "%i", context->oom_score_adjust);
1078 if (write_one_line_file("/proc/self/oom_score_adj", t) < 0) {
1079 /* Compatibility with Linux <= 2.6.35 */
1083 adj = (context->oom_score_adjust * -OOM_DISABLE) / OOM_SCORE_ADJ_MAX;
1084 adj = CLAMP(adj, OOM_DISABLE, OOM_ADJUST_MAX);
1086 snprintf(t, sizeof(t), "%i", adj);
1089 if (write_one_line_file("/proc/self/oom_adj", t) < 0) {
1090 r = EXIT_OOM_ADJUST;
1096 if (context->nice_set)
1097 if (setpriority(PRIO_PROCESS, 0, context->nice) < 0) {
1102 if (context->cpu_sched_set) {
1103 struct sched_param param;
1106 param.sched_priority = context->cpu_sched_priority;
1108 if (sched_setscheduler(0, context->cpu_sched_policy |
1109 (context->cpu_sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0), ¶m) < 0) {
1110 r = EXIT_SETSCHEDULER;
1115 if (context->cpuset)
1116 if (sched_setaffinity(0, CPU_ALLOC_SIZE(context->cpuset_ncpus), context->cpuset) < 0) {
1117 r = EXIT_CPUAFFINITY;
1121 if (context->ioprio_set)
1122 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
1127 if (context->timer_slack_nsec_set)
1128 if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
1129 r = EXIT_TIMERSLACK;
1133 if (context->utmp_id)
1134 utmp_put_init_process(0, context->utmp_id, getpid(), getsid(0), context->tty_path);
1136 if (context->user) {
1137 username = context->user;
1138 if (get_user_creds(&username, &uid, &gid, &home) < 0) {
1143 if (is_terminal_input(context->std_input))
1144 if (chown_terminal(STDIN_FILENO, uid) < 0) {
1151 if (context->pam_name && username) {
1152 if (setup_pam(context->pam_name, username, context->tty_path, &pam_env, fds, n_fds) < 0) {
1159 if (apply_permissions)
1160 if (enforce_groups(context, username, uid) < 0) {
1165 umask(context->umask);
1167 if (strv_length(context->read_write_dirs) > 0 ||
1168 strv_length(context->read_only_dirs) > 0 ||
1169 strv_length(context->inaccessible_dirs) > 0 ||
1170 context->mount_flags != MS_SHARED ||
1171 context->private_tmp)
1172 if ((r = setup_namespace(
1173 context->read_write_dirs,
1174 context->read_only_dirs,
1175 context->inaccessible_dirs,
1176 context->private_tmp,
1177 context->mount_flags)) < 0)
1181 if (context->root_directory)
1182 if (chroot(context->root_directory) < 0) {
1187 if (chdir(context->working_directory ? context->working_directory : "/") < 0) {
1195 if (asprintf(&d, "%s/%s",
1196 context->root_directory ? context->root_directory : "",
1197 context->working_directory ? context->working_directory : "") < 0) {
1211 /* We repeat the fd closing here, to make sure that
1212 * nothing is leaked from the PAM modules */
1213 if (close_all_fds(fds, n_fds) < 0 ||
1214 shift_fds(fds, n_fds) < 0 ||
1215 flags_fds(fds, n_fds, context->non_blocking) < 0) {
1220 if (apply_permissions) {
1222 for (i = 0; i < RLIMIT_NLIMITS; i++) {
1223 if (!context->rlimit[i])
1226 if (setrlimit(i, context->rlimit[i]) < 0) {
1233 if (enforce_user(context, uid) < 0) {
1238 /* PR_GET_SECUREBITS is not priviliged, while
1239 * PR_SET_SECUREBITS is. So to suppress
1240 * potential EPERMs we'll try not to call
1241 * PR_SET_SECUREBITS unless necessary. */
1242 if (prctl(PR_GET_SECUREBITS) != context->secure_bits)
1243 if (prctl(PR_SET_SECUREBITS, context->secure_bits) < 0) {
1244 r = EXIT_SECUREBITS;
1248 if (context->capabilities)
1249 if (cap_set_proc(context->capabilities) < 0) {
1250 r = EXIT_CAPABILITIES;
1255 if (!(our_env = new0(char*, 6))) {
1261 if (asprintf(our_env + n_env++, "LISTEN_PID=%lu", (unsigned long) getpid()) < 0 ||
1262 asprintf(our_env + n_env++, "LISTEN_FDS=%u", n_fds) < 0) {
1268 if (asprintf(our_env + n_env++, "HOME=%s", home) < 0) {
1274 if (asprintf(our_env + n_env++, "LOGNAME=%s", username) < 0 ||
1275 asprintf(our_env + n_env++, "USER=%s", username) < 0) {
1282 if (!(final_env = strv_env_merge(
1286 context->environment,
1293 if (!(final_argv = replace_env_argv(argv, final_env))) {
1298 execve(command->path, final_argv, final_env);
1303 strv_free(final_env);
1305 strv_free(final_argv);
1307 if (saved_stdin >= 0)
1308 close_nointr_nofail(saved_stdin);
1310 if (saved_stdout >= 0)
1311 close_nointr_nofail(saved_stdout);
1316 /* We add the new process to the cgroup both in the child (so
1317 * that we can be sure that no user code is ever executed
1318 * outside of the cgroup) and in the parent (so that we can be
1319 * sure that when we kill the cgroup the process will be
1321 if (cgroup_bondings)
1322 cgroup_bonding_install_list(cgroup_bondings, pid);
1324 log_debug("Forked %s as %lu", command->path, (unsigned long) pid);
1326 exec_status_start(&command->exec_status, pid);
1332 void exec_context_init(ExecContext *c) {
1336 c->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 0);
1337 c->cpu_sched_policy = SCHED_OTHER;
1338 c->syslog_priority = LOG_DAEMON|LOG_INFO;
1339 c->syslog_level_prefix = true;
1340 c->mount_flags = MS_SHARED;
1341 c->kill_signal = SIGTERM;
1344 void exec_context_done(ExecContext *c) {
1349 strv_free(c->environment);
1350 c->environment = NULL;
1352 for (l = 0; l < ELEMENTSOF(c->rlimit); l++) {
1354 c->rlimit[l] = NULL;
1357 free(c->working_directory);
1358 c->working_directory = NULL;
1359 free(c->root_directory);
1360 c->root_directory = NULL;
1365 free(c->tcpwrap_name);
1366 c->tcpwrap_name = NULL;
1368 free(c->syslog_identifier);
1369 c->syslog_identifier = NULL;
1377 strv_free(c->supplementary_groups);
1378 c->supplementary_groups = NULL;
1383 if (c->capabilities) {
1384 cap_free(c->capabilities);
1385 c->capabilities = NULL;
1388 strv_free(c->read_only_dirs);
1389 c->read_only_dirs = NULL;
1391 strv_free(c->read_write_dirs);
1392 c->read_write_dirs = NULL;
1394 strv_free(c->inaccessible_dirs);
1395 c->inaccessible_dirs = NULL;
1398 CPU_FREE(c->cpuset);
1401 void exec_command_done(ExecCommand *c) {
1411 void exec_command_done_array(ExecCommand *c, unsigned n) {
1414 for (i = 0; i < n; i++)
1415 exec_command_done(c+i);
1418 void exec_command_free_list(ExecCommand *c) {
1422 LIST_REMOVE(ExecCommand, command, c, i);
1423 exec_command_done(i);
1428 void exec_command_free_array(ExecCommand **c, unsigned n) {
1431 for (i = 0; i < n; i++) {
1432 exec_command_free_list(c[i]);
1437 static void strv_fprintf(FILE *f, char **l) {
1443 fprintf(f, " %s", *g);
1446 void exec_context_dump(ExecContext *c, FILE* f, const char *prefix) {
1458 "%sWorkingDirectory: %s\n"
1459 "%sRootDirectory: %s\n"
1460 "%sNonBlocking: %s\n"
1461 "%sPrivateTmp: %s\n",
1463 prefix, c->working_directory ? c->working_directory : "/",
1464 prefix, c->root_directory ? c->root_directory : "/",
1465 prefix, yes_no(c->non_blocking),
1466 prefix, yes_no(c->private_tmp));
1469 for (e = c->environment; *e; e++)
1470 fprintf(f, "%sEnvironment: %s\n", prefix, *e);
1472 if (c->tcpwrap_name)
1474 "%sTCPWrapName: %s\n",
1475 prefix, c->tcpwrap_name);
1482 if (c->oom_score_adjust_set)
1484 "%sOOMScoreAdjust: %i\n",
1485 prefix, c->oom_score_adjust);
1487 for (i = 0; i < RLIM_NLIMITS; i++)
1489 fprintf(f, "%s%s: %llu\n", prefix, rlimit_to_string(i), (unsigned long long) c->rlimit[i]->rlim_max);
1493 "%sIOSchedulingClass: %s\n"
1494 "%sIOPriority: %i\n",
1495 prefix, ioprio_class_to_string(IOPRIO_PRIO_CLASS(c->ioprio)),
1496 prefix, (int) IOPRIO_PRIO_DATA(c->ioprio));
1498 if (c->cpu_sched_set)
1500 "%sCPUSchedulingPolicy: %s\n"
1501 "%sCPUSchedulingPriority: %i\n"
1502 "%sCPUSchedulingResetOnFork: %s\n",
1503 prefix, sched_policy_to_string(c->cpu_sched_policy),
1504 prefix, c->cpu_sched_priority,
1505 prefix, yes_no(c->cpu_sched_reset_on_fork));
1508 fprintf(f, "%sCPUAffinity:", prefix);
1509 for (i = 0; i < c->cpuset_ncpus; i++)
1510 if (CPU_ISSET_S(i, CPU_ALLOC_SIZE(c->cpuset_ncpus), c->cpuset))
1511 fprintf(f, " %i", i);
1515 if (c->timer_slack_nsec_set)
1516 fprintf(f, "%sTimerSlackNSec: %lu\n", prefix, c->timer_slack_nsec);
1519 "%sStandardInput: %s\n"
1520 "%sStandardOutput: %s\n"
1521 "%sStandardError: %s\n",
1522 prefix, exec_input_to_string(c->std_input),
1523 prefix, exec_output_to_string(c->std_output),
1524 prefix, exec_output_to_string(c->std_error));
1529 prefix, c->tty_path);
1531 if (c->std_output == EXEC_OUTPUT_SYSLOG || c->std_output == EXEC_OUTPUT_KMSG ||
1532 c->std_error == EXEC_OUTPUT_SYSLOG || c->std_error == EXEC_OUTPUT_KMSG)
1534 "%sSyslogFacility: %s\n"
1535 "%sSyslogLevel: %s\n",
1536 prefix, log_facility_to_string(LOG_FAC(c->syslog_priority)),
1537 prefix, log_level_to_string(LOG_PRI(c->syslog_priority)));
1539 if (c->capabilities) {
1541 if ((t = cap_to_text(c->capabilities, NULL))) {
1542 fprintf(f, "%sCapabilities: %s\n",
1549 fprintf(f, "%sSecure Bits:%s%s%s%s%s%s\n",
1551 (c->secure_bits & SECURE_KEEP_CAPS) ? " keep-caps" : "",
1552 (c->secure_bits & SECURE_KEEP_CAPS_LOCKED) ? " keep-caps-locked" : "",
1553 (c->secure_bits & SECURE_NO_SETUID_FIXUP) ? " no-setuid-fixup" : "",
1554 (c->secure_bits & SECURE_NO_SETUID_FIXUP_LOCKED) ? " no-setuid-fixup-locked" : "",
1555 (c->secure_bits & SECURE_NOROOT) ? " noroot" : "",
1556 (c->secure_bits & SECURE_NOROOT_LOCKED) ? "noroot-locked" : "");
1558 if (c->capability_bounding_set_drop) {
1559 fprintf(f, "%sCapabilityBoundingSetDrop:", prefix);
1561 for (i = 0; i <= CAP_LAST_CAP; i++)
1562 if (c->capability_bounding_set_drop & (1 << i)) {
1565 if ((t = cap_to_name(i))) {
1566 fprintf(f, " %s", t);
1575 fprintf(f, "%sUser: %s\n", prefix, c->user);
1577 fprintf(f, "%sGroup: %s\n", prefix, c->group);
1579 if (strv_length(c->supplementary_groups) > 0) {
1580 fprintf(f, "%sSupplementaryGroups:", prefix);
1581 strv_fprintf(f, c->supplementary_groups);
1586 fprintf(f, "%sPAMName: %s\n", prefix, c->pam_name);
1588 if (strv_length(c->read_write_dirs) > 0) {
1589 fprintf(f, "%sReadWriteDirs:", prefix);
1590 strv_fprintf(f, c->read_write_dirs);
1594 if (strv_length(c->read_only_dirs) > 0) {
1595 fprintf(f, "%sReadOnlyDirs:", prefix);
1596 strv_fprintf(f, c->read_only_dirs);
1600 if (strv_length(c->inaccessible_dirs) > 0) {
1601 fprintf(f, "%sInaccessibleDirs:", prefix);
1602 strv_fprintf(f, c->inaccessible_dirs);
1608 "%sKillSignal: SIG%s\n",
1609 prefix, kill_mode_to_string(c->kill_mode),
1610 prefix, signal_to_string(c->kill_signal));
1614 "%sUtmpIdentifier: %s\n",
1615 prefix, c->utmp_id);
1618 void exec_status_start(ExecStatus *s, pid_t pid) {
1623 dual_timestamp_get(&s->start_timestamp);
1626 void exec_status_exit(ExecStatus *s, pid_t pid, int code, int status, const char *utmp_id) {
1629 if ((s->pid && s->pid != pid) ||
1630 !s->start_timestamp.realtime <= 0)
1634 dual_timestamp_get(&s->exit_timestamp);
1640 utmp_put_dead_process(utmp_id, pid, code, status);
1643 void exec_status_dump(ExecStatus *s, FILE *f, const char *prefix) {
1644 char buf[FORMAT_TIMESTAMP_MAX];
1657 prefix, (unsigned long) s->pid);
1659 if (s->start_timestamp.realtime > 0)
1661 "%sStart Timestamp: %s\n",
1662 prefix, format_timestamp(buf, sizeof(buf), s->start_timestamp.realtime));
1664 if (s->exit_timestamp.realtime > 0)
1666 "%sExit Timestamp: %s\n"
1668 "%sExit Status: %i\n",
1669 prefix, format_timestamp(buf, sizeof(buf), s->exit_timestamp.realtime),
1670 prefix, sigchld_code_to_string(s->code),
1674 char *exec_command_line(char **argv) {
1682 STRV_FOREACH(a, argv)
1685 if (!(n = new(char, k)))
1689 STRV_FOREACH(a, argv) {
1696 if (strpbrk(*a, WHITESPACE)) {
1707 /* FIXME: this doesn't really handle arguments that have
1708 * spaces and ticks in them */
1713 void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
1715 const char *prefix2;
1724 p2 = strappend(prefix, "\t");
1725 prefix2 = p2 ? p2 : prefix;
1727 cmd = exec_command_line(c->argv);
1730 "%sCommand Line: %s\n",
1731 prefix, cmd ? cmd : strerror(ENOMEM));
1735 exec_status_dump(&c->exec_status, f, prefix2);
1740 void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
1746 LIST_FOREACH(command, c, c)
1747 exec_command_dump(c, f, prefix);
1750 void exec_command_append_list(ExecCommand **l, ExecCommand *e) {
1757 /* It's kinda important that we keep the order here */
1758 LIST_FIND_TAIL(ExecCommand, command, *l, end);
1759 LIST_INSERT_AFTER(ExecCommand, command, *l, end, e);
1764 int exec_command_set(ExecCommand *c, const char *path, ...) {
1772 l = strv_new_ap(path, ap);
1778 if (!(p = strdup(path))) {
1792 static const char* const exec_input_table[_EXEC_INPUT_MAX] = {
1793 [EXEC_INPUT_NULL] = "null",
1794 [EXEC_INPUT_TTY] = "tty",
1795 [EXEC_INPUT_TTY_FORCE] = "tty-force",
1796 [EXEC_INPUT_TTY_FAIL] = "tty-fail",
1797 [EXEC_INPUT_SOCKET] = "socket"
1800 static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = {
1801 [EXEC_OUTPUT_INHERIT] = "inherit",
1802 [EXEC_OUTPUT_NULL] = "null",
1803 [EXEC_OUTPUT_TTY] = "tty",
1804 [EXEC_OUTPUT_SYSLOG] = "syslog",
1805 [EXEC_OUTPUT_KMSG] = "kmsg",
1806 [EXEC_OUTPUT_SOCKET] = "socket"
1809 DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput);
1811 DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput);