2 * Copyright (c) 2009-2013 Todd C. Miller <Todd.Miller@courtesan.com>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 #include <sys/types.h>
20 #ifdef HAVE_SYS_SYSMACROS_H
21 # include <sys/sysmacros.h>
23 #include <sys/socket.h>
27 #include <sys/ioctl.h>
28 #ifdef HAVE_SYS_SELECT_H
29 # include <sys/select.h>
30 #endif /* HAVE_SYS_SELECT_H */
39 #endif /* STDC_HEADERS */
42 #endif /* HAVE_STRING_H */
45 #endif /* HAVE_STRINGS_H */
48 #endif /* HAVE_UNISTD_H */
49 #if TIME_WITH_SYS_TIME
58 #include "sudo_exec.h"
59 #include "sudo_plugin.h"
60 #include "sudo_plugin_int.h"
62 /* We keep a tailq of signals to forward to child. */
64 struct sigforward *prev, *next;
67 TQ_DECLARE(sigforward)
68 static struct sigforward_list sigfwd_list;
69 static pid_t ppgrp = -1;
71 volatile pid_t cmnd_pid = -1;
73 static int dispatch_signals(int sv[2], pid_t child, int log_io,
74 struct command_status *cstat);
75 static int dispatch_pending_signals(struct command_status *cstat);
76 static void forward_signals(int fd);
77 static void schedule_signal(int signo);
79 static void handler_user_only(int s, siginfo_t *info, void *context);
83 * Fork and execute a command, returns the child's pid.
84 * Sends errno back on sv[1] if execve() fails.
86 static int fork_cmnd(struct command_details *details, int sv[2])
88 struct command_status cstat;
90 debug_decl(fork_cmnd, SUDO_DEBUG_EXEC)
92 ppgrp = getpgrp(); /* parent's process group */
95 * Handle suspend/restore of sudo and the command.
96 * In most cases, the command will be in the same process group as
97 * sudo and job control will "just work". However, if the command
98 * changes its process group ID and does not change it back (or is
99 * kill by SIGSTOP which is not catchable), we need to resume the
100 * command manually. Also, if SIGTSTP is sent directly to sudo,
101 * we need to suspend the command, and then suspend ourself, restoring
102 * the default SIGTSTP handler temporarily.
104 * XXX - currently we send SIGCONT upon resume in some cases where
105 * we don't need to (e.g. command pgrp == parent pgrp).
107 memset(&sa, 0, sizeof(sa));
108 sigfillset(&sa.sa_mask);
109 sa.sa_flags = SA_INTERRUPT; /* do not restart syscalls */
111 sa.sa_flags |= SA_SIGINFO;
112 sa.sa_sigaction = handler;
114 sa.sa_handler = handler;
116 sudo_sigaction(SIGCONT, &sa, NULL);
118 sa.sa_sigaction = handler_user_only;
120 sudo_sigaction(SIGTSTP, &sa, NULL);
123 * The policy plugin's session init must be run before we fork
124 * or certain pam modules won't be able to track their state.
126 if (policy_init_session(details) != true)
127 fatalx(_("policy plugin failed session initialization"));
129 cmnd_pid = sudo_debug_fork();
132 fatal(_("unable to fork"));
137 close(signal_pipe[0]);
138 close(signal_pipe[1]);
139 fcntl(sv[1], F_SETFD, FD_CLOEXEC);
140 exec_cmnd(details, &cstat, &sv[1]);
141 send(sv[1], &cstat, sizeof(cstat), 0);
142 sudo_debug_exit_int(__func__, __FILE__, __LINE__, sudo_debug_subsys, 1);
145 sudo_debug_printf(SUDO_DEBUG_INFO, "executed %s, pid %d", details->command,
147 debug_return_int(cmnd_pid);
151 * Setup the execution environment and execute the command.
152 * If SELinux is enabled, run the command via sesh, otherwise
153 * execute it directly.
154 * If the exec fails, cstat is filled in with the value of errno.
157 exec_cmnd(struct command_details *details, struct command_status *cstat,
160 debug_decl(exec_cmnd, SUDO_DEBUG_EXEC)
163 if (exec_setup(details, NULL, -1) == true) {
164 /* headed for execve() */
165 sudo_debug_execve(SUDO_DEBUG_INFO, details->command,
166 details->argv, details->envp);
167 if (details->closefrom >= 0) {
168 int maxfd = details->closefrom;
169 /* Preserve back channel if present. */
172 (void)fcntl(maxfd, F_SETFD, FD_CLOEXEC);
175 if (sudo_debug_fd_set(maxfd) != -1)
180 if (ISSET(details->flags, CD_RBAC_ENABLED)) {
181 selinux_execve(details->command, details->argv, details->envp,
182 ISSET(details->flags, CD_NOEXEC));
186 sudo_execve(details->command, details->argv, details->envp,
187 ISSET(details->flags, CD_NOEXEC));
189 cstat->type = CMD_ERRNO;
191 sudo_debug_printf(SUDO_DEBUG_ERROR, "unable to exec %s: %s",
192 details->command, strerror(errno));
198 * Execute a command, potentially in a pty with I/O loggging, and
199 * wait for it to finish.
200 * This is a little bit tricky due to how POSIX job control works and
201 * we fact that we have two different controlling terminals to deal with.
204 sudo_execute(struct command_details *details, struct command_status *cstat)
206 int maxfd, n, nready, sv[2];
207 const char *utmp_user = NULL;
213 debug_decl(sudo_execute, SUDO_DEBUG_EXEC)
215 dispatch_pending_signals(cstat);
217 /* If running in background mode, fork and exit. */
218 if (ISSET(details->flags, CD_BACKGROUND)) {
219 switch (sudo_debug_fork()) {
221 cstat->type = CMD_ERRNO;
223 debug_return_int(-1);
225 /* child continues without controlling terminal */
229 /* parent exits (but does not flush buffers) */
230 sudo_debug_exit_int(__func__, __FILE__, __LINE__,
231 sudo_debug_subsys, 0);
237 * If we have an I/O plugin or the policy plugin has requested one, we
238 * need to allocate a pty. It is OK to set log_io in the pty-only case
239 * as the io plugin tailqueue will be empty and no I/O logging will occur.
241 if (!tq_empty(&io_plugins) || ISSET(details->flags, CD_USE_PTY)) {
243 if (ISSET(details->flags, CD_SET_UTMP))
244 utmp_user = details->utmp_user ? details->utmp_user : user_details.username;
245 sudo_debug_printf(SUDO_DEBUG_INFO, "allocate pty for I/O logging");
246 pty_setup(details->euid, user_details.tty, utmp_user);
247 } else if (!ISSET(details->flags, CD_SET_TIMEOUT) &&
248 policy_plugin.u.policy->close == NULL) {
249 /* If no I/O logging, timeout or policy close we can exec directly. */
250 exec_cmnd(details, cstat, NULL);
255 * We communicate with the child over a bi-directional pair of sockets.
256 * Parent sends signal info to child and child sends back wait status.
258 if (socketpair(PF_UNIX, SOCK_DGRAM, 0, sv) == -1)
259 fatal(_("unable to create sockets"));
262 * Signals to forward to the child process (excluding SIGALRM and SIGCHLD).
263 * We block all other signals while running the signal handler.
264 * Note: HP-UX select() will not be interrupted if SA_RESTART set.
266 memset(&sa, 0, sizeof(sa));
267 sigfillset(&sa.sa_mask);
268 sa.sa_flags = SA_INTERRUPT; /* do not restart syscalls */
270 sa.sa_flags |= SA_SIGINFO;
271 sa.sa_sigaction = handler;
273 sa.sa_handler = handler;
275 sudo_sigaction(SIGTERM, &sa, NULL);
276 sudo_sigaction(SIGALRM, &sa, NULL); /* XXX - only if there is a timeout */
277 sudo_sigaction(SIGCHLD, &sa, NULL);
278 sudo_sigaction(SIGPIPE, &sa, NULL);
279 sudo_sigaction(SIGUSR1, &sa, NULL);
280 sudo_sigaction(SIGUSR2, &sa, NULL);
283 * When not running the command in a pty, we do not want to
284 * forward signals generated by the kernel that the child will
285 * already have received either by virtue of being in the
286 * controlling tty's process group (SIGINT, SIGQUIT) or because
287 * the session is terminating (SIGHUP).
291 sa.sa_flags |= SA_SIGINFO;
292 sa.sa_sigaction = handler_user_only;
295 sudo_sigaction(SIGHUP, &sa, NULL);
296 sudo_sigaction(SIGINT, &sa, NULL);
297 sudo_sigaction(SIGQUIT, &sa, NULL);
299 /* Max fd we will be selecting on. */
300 maxfd = MAX(sv[0], signal_pipe[0]);
303 * Child will run the command in the pty, parent will pass data
304 * to and from pty. Adjusts maxfd as needed.
307 child = fork_pty(details, sv, &maxfd, &omask);
309 child = fork_cmnd(details, sv);
312 /* Set command timeout if specified. */
313 if (ISSET(details->flags, CD_SET_TIMEOUT))
314 alarm(details->timeout);
317 * I/O logging must be in the C locale for floating point numbers
318 * to be logged consistently.
320 setlocale(LC_ALL, "C");
323 * In the event loop we pass input from user tty to master
324 * and pass output from master to stdout and IO plugin.
326 fdsr = emalloc2(howmany(maxfd + 1, NFDBITS), sizeof(fd_mask));
327 fdsw = emalloc2(howmany(maxfd + 1, NFDBITS), sizeof(fd_mask));
329 memset(fdsw, 0, howmany(maxfd + 1, NFDBITS) * sizeof(fd_mask));
330 memset(fdsr, 0, howmany(maxfd + 1, NFDBITS) * sizeof(fd_mask));
332 FD_SET(signal_pipe[0], fdsr);
334 if (!tq_empty(&sigfwd_list))
337 fd_set_iobs(fdsr, fdsw); /* XXX - better name */
338 nready = select(maxfd + 1, fdsr, fdsw, NULL, NULL);
339 sudo_debug_printf(SUDO_DEBUG_DEBUG, "select returns %d", nready);
341 if (errno == EINTR || errno == ENOMEM)
343 if (errno == EBADF || errno == EIO) {
344 /* One of the ttys must have gone away. */
347 warning(_("select failed"));
348 sudo_debug_printf(SUDO_DEBUG_ERROR,
349 "select failure, terminating child");
350 schedule_signal(SIGKILL);
351 forward_signals(sv[0]);
354 if (FD_ISSET(sv[0], fdsw)) {
355 forward_signals(sv[0]);
357 if (FD_ISSET(signal_pipe[0], fdsr)) {
358 n = dispatch_signals(sv, child, log_io, cstat);
360 /* Child has exited, cstat is set, we are done. */
364 /* Error reading signal_pipe[0], should not happen. */
367 /* Restart event loop so signals get sent to child immediately. */
370 if (FD_ISSET(sv[0], fdsr)) {
371 /* read child status */
372 n = recv(sv[0], cstat, sizeof(*cstat), 0);
373 if (n != sizeof(*cstat)) {
378 * If not logging I/O we may receive ECONNRESET when
379 * the command is executed and sv is closed.
380 * It is safe to ignore this.
382 if (log_io && errno != EAGAIN) {
383 cstat->type = CMD_ERRNO;
387 sudo_debug_printf(SUDO_DEBUG_ERROR,
388 "failed to read child status: %s", strerror(errno));
390 /* Short read or EOF. */
391 sudo_debug_printf(SUDO_DEBUG_ERROR,
392 "failed to read child status: %s",
393 n ? "short read" : "EOF");
394 /* XXX - should set cstat */
398 if (cstat->type == CMD_PID) {
400 * Once we know the command's pid we can unblock
401 * signals which ere blocked in fork_pty(). This
402 * avoids a race between exec of the command and
403 * receipt of a fatal signal from it.
405 cmnd_pid = cstat->val;
406 sudo_debug_printf(SUDO_DEBUG_INFO, "executed %s, pid %d",
407 details->command, (int)cmnd_pid);
409 sigprocmask(SIG_SETMASK, &omask, NULL);
410 } else if (cstat->type == CMD_WSTATUS) {
411 if (WIFSTOPPED(cstat->val)) {
412 /* Suspend parent and tell child how to resume on return. */
413 sudo_debug_printf(SUDO_DEBUG_INFO,
414 "child stopped, suspending parent");
415 n = suspend_parent(WSTOPSIG(cstat->val));
419 /* Child exited or was killed, either way we are done. */
420 sudo_debug_printf(SUDO_DEBUG_INFO, "child exited or was killed");
423 } else if (cstat->type == CMD_ERRNO) {
424 /* Child was unable to execute command or broken pipe. */
425 sudo_debug_printf(SUDO_DEBUG_INFO, "errno from child: %s",
426 strerror(cstat->val));
431 if (perform_io(fdsr, fdsw, cstat) != 0) {
432 /* I/O error, kill child if still alive and finish. */
433 sudo_debug_printf(SUDO_DEBUG_ERROR, "I/O error, terminating child");
434 schedule_signal(SIGKILL);
435 forward_signals(sv[0]);
441 /* Flush any remaining output and free pty-related memory. */
446 if (ISSET(details->flags, CD_RBAC_ENABLED)) {
447 /* This is probably not needed in log_io mode. */
448 if (selinux_restore_tty() != 0)
449 warningx(_("unable to restore tty label"));
455 while (!tq_empty(&sigfwd_list)) {
456 struct sigforward *sigfwd = tq_first(&sigfwd_list);
457 tq_remove(&sigfwd_list, sigfwd);
461 debug_return_int(cstat->type == CMD_ERRNO ? -1 : 0);
465 * Read signals on signal_pipe written by handler().
466 * Returns -1 on error, 0 on child exit, else 1.
469 dispatch_signals(int sv[2], pid_t child, int log_io, struct command_status *cstat)
471 char signame[SIG2STR_MAX];
476 debug_decl(dispatch_signals, SUDO_DEBUG_EXEC)
479 /* read signal pipe */
480 nread = read(signal_pipe[0], &signo, sizeof(signo));
482 /* It should not be possible to get EOF but just in case. */
485 /* Restart if interrupted by signal so the pipe doesn't fill. */
488 /* If pipe is empty, we are done. */
491 sudo_debug_printf(SUDO_DEBUG_ERROR, "error reading signal pipe %s",
493 cstat->type = CMD_ERRNO;
495 debug_return_int(-1);
497 if (sig2str(signo, signame) == -1)
498 snprintf(signame, sizeof(signame), "%d", signo);
499 sudo_debug_printf(SUDO_DEBUG_DIAG, "received SIG%s", signame);
500 if (signo == SIGCHLD) {
502 * If logging I/O, child is the intermediate process,
503 * otherwise it is the command itself.
506 pid = waitpid(child, &status, WUNTRACED|WNOHANG);
507 } while (pid == -1 && errno == EINTR);
511 * On BSD we get ECONNRESET on sv[0] if monitor dies
512 * and select() will return with sv[0] readable.
513 * On Linux that doesn't appear to happen so if the
514 * monitor dies, shut down the socketpair to force a
515 * select() notification.
517 (void) shutdown(sv[0], SHUT_WR);
519 if (WIFSTOPPED(status)) {
521 * Save the controlling terminal's process group
522 * so we can restore it after we resume, if needed.
523 * Most well-behaved shells change the pgrp back to
524 * its original value before suspending so we must
525 * not try to restore in that case, lest we race with
526 * the child upon resume, potentially stopping sudo
527 * with SIGTTOU while the command continues to run.
530 pid_t saved_pgrp = (pid_t)-1;
531 int signo = WSTOPSIG(status);
532 int fd = open(_PATH_TTY, O_RDWR|O_NOCTTY, 0);
534 if ((saved_pgrp = tcgetpgrp(fd)) == ppgrp)
537 if (signo == SIGTSTP) {
538 memset(&sa, 0, sizeof(sa));
539 sigemptyset(&sa.sa_mask);
540 sa.sa_flags = SA_RESTART;
541 sa.sa_handler = SIG_DFL;
542 sudo_sigaction(SIGTSTP, &sa, &osa);
544 if (kill(getpid(), signo) != 0)
545 warning("kill(%d, SIG%s)", (int)getpid(), signame);
546 if (signo == SIGTSTP)
547 sudo_sigaction(SIGTSTP, &osa, NULL);
550 * Restore command's process group if different.
551 * Otherwise, we cannot resume some shells.
553 if (saved_pgrp != (pid_t)-1)
554 (void)tcsetpgrp(fd, saved_pgrp);
558 /* Child has exited, we are done. */
559 cstat->type = CMD_WSTATUS;
567 /* Schedule signo to be forwared to the child. */
568 schedule_signal(signo);
570 /* Nothing listening on sv[0], send directly. */
571 if (signo == SIGALRM)
572 terminate_command(child, false);
573 else if (kill(child, signo) != 0)
574 warning("kill(%d, SIG%s)", (int)child, signame);
582 * Drain pending signals from signale_pipe written by sudo_handler().
583 * Handles the case where the signal was sent to us before
584 * we have executed the command.
585 * Returns 1 if we should terminate, else 0.
588 dispatch_pending_signals(struct command_status *cstat)
592 unsigned char signo = 0;
594 debug_decl(dispatch_pending_signals, SUDO_DEBUG_EXEC)
597 nread = read(signal_pipe[0], &signo, sizeof(signo));
599 /* It should not be possible to get EOF but just in case. */
602 /* Restart if interrupted by signal so the pipe doesn't fill. */
605 /* If pipe is empty, we are done. */
608 sudo_debug_printf(SUDO_DEBUG_ERROR, "error reading signal pipe %s",
610 cstat->type = CMD_ERRNO;
615 /* Take the first terminal signal. */
616 if (signo == SIGINT || signo == SIGQUIT) {
617 cstat->type = CMD_WSTATUS;
618 cstat->val = signo + 128;
623 /* Only stop if we haven't already been terminated. */
624 if (signo == SIGTSTP)
626 memset(&sa, 0, sizeof(sa));
627 sigemptyset(&sa.sa_mask);
628 sa.sa_flags = SA_RESTART;
629 sa.sa_handler = SIG_DFL;
630 sudo_sigaction(SIGTSTP, &sa, NULL);
631 if (kill(getpid(), SIGTSTP) != 0)
632 warning("kill(%d, SIGTSTP)", (int)getpid());
633 /* No need to reinstall SIGTSTP handler. */
635 debug_return_int(rval);
639 * Forward signals in sigfwd_list to child listening on fd.
642 forward_signals(int sock)
644 char signame[SIG2STR_MAX];
645 struct sigforward *sigfwd;
646 struct command_status cstat;
648 debug_decl(forward_signals, SUDO_DEBUG_EXEC)
650 while (!tq_empty(&sigfwd_list)) {
651 sigfwd = tq_first(&sigfwd_list);
652 if (sigfwd->signo == SIGCONT_FG)
653 strlcpy(signame, "CONT_FG", sizeof(signame));
654 else if (sigfwd->signo == SIGCONT_BG)
655 strlcpy(signame, "CONT_BG", sizeof(signame));
656 else if (sig2str(sigfwd->signo, signame) == -1)
657 snprintf(signame, sizeof(signame), "%d", sigfwd->signo);
658 sudo_debug_printf(SUDO_DEBUG_INFO,
659 "sending SIG%s to child over backchannel", signame);
660 cstat.type = CMD_SIGNO;
661 cstat.val = sigfwd->signo;
663 nsent = send(sock, &cstat, sizeof(cstat), 0);
664 } while (nsent == -1 && errno == EINTR);
665 tq_remove(&sigfwd_list, sigfwd);
667 if (nsent != sizeof(cstat)) {
668 if (errno == EPIPE) {
669 sudo_debug_printf(SUDO_DEBUG_ERROR,
670 "broken pipe writing to child over backchannel");
671 /* Other end of socket gone, empty out sigfwd_list. */
672 while (!tq_empty(&sigfwd_list)) {
673 sigfwd = tq_first(&sigfwd_list);
674 tq_remove(&sigfwd_list, sigfwd);
677 /* XXX - child (monitor) is dead, we should exit too? */
686 * Schedule a signal to be forwared.
689 schedule_signal(int signo)
691 struct sigforward *sigfwd;
692 char signame[SIG2STR_MAX];
693 debug_decl(schedule_signal, SUDO_DEBUG_EXEC)
695 if (signo == SIGCONT_FG)
696 strlcpy(signame, "CONT_FG", sizeof(signame));
697 else if (signo == SIGCONT_BG)
698 strlcpy(signame, "CONT_BG", sizeof(signame));
699 else if (sig2str(signo, signame) == -1)
700 snprintf(signame, sizeof(signame), "%d", signo);
701 sudo_debug_printf(SUDO_DEBUG_DIAG, "scheduled SIG%s for child", signame);
703 sigfwd = ecalloc(1, sizeof(*sigfwd));
704 sigfwd->prev = sigfwd;
705 /* sigfwd->next = NULL; */
706 sigfwd->signo = signo;
707 tq_append(&sigfwd_list, sigfwd);
713 * Generic handler for signals passed from parent -> child.
714 * The other end of signal_pipe is checked in the main event loop.
718 handler(int s, siginfo_t *info, void *context)
720 unsigned char signo = (unsigned char)s;
723 * If the signal came from the command we ran, just ignore
724 * it since we don't want the child to indirectly kill itself.
725 * This can happen with, e.g. BSD-derived versions of reboot
726 * that call kill(-1, SIGTERM) to kill all other processes.
728 if (info != NULL && info->si_code == SI_USER && info->si_pid == cmnd_pid)
732 * The pipe is non-blocking, if we overflow the kernel's pipe
733 * buffer we drop the signal. This is not a problem in practice.
735 ignore_result(write(signal_pipe[1], &signo, sizeof(signo)));
741 unsigned char signo = (unsigned char)s;
744 * The pipe is non-blocking, if we overflow the kernel's pipe
745 * buffer we drop the signal. This is not a problem in practice.
747 ignore_result(write(signal_pipe[1], &signo, sizeof(signo)));
753 * Generic handler for signals passed from parent -> child.
754 * The other end of signal_pipe is checked in the main event loop.
755 * This version is for the non-pty case and does not forward
756 * signals that are generated by the kernel.
759 handler_user_only(int s, siginfo_t *info, void *context)
761 unsigned char signo = (unsigned char)s;
763 /* Only forward user-generated signals. */
764 if (info != NULL && info->si_code == SI_USER) {
766 * The pipe is non-blocking, if we overflow the kernel's pipe
767 * buffer we drop the signal. This is not a problem in practice.
769 ignore_result(write(signal_pipe[1], &signo, sizeof(signo)));
772 #endif /* SA_SIGINFO */
775 * Open a pipe and make both ends non-blocking.
776 * Returns 0 on success and -1 on error.
779 pipe_nonblock(int fds[2])
782 debug_decl(pipe_nonblock, SUDO_DEBUG_EXEC)
786 flags = fcntl(fds[0], F_GETFL, 0);
787 if (flags != -1 && !ISSET(flags, O_NONBLOCK))
788 rval = fcntl(fds[0], F_SETFL, flags | O_NONBLOCK);
790 flags = fcntl(fds[1], F_GETFL, 0);
791 if (flags != -1 && !ISSET(flags, O_NONBLOCK))
792 rval = fcntl(fds[1], F_SETFL, flags | O_NONBLOCK);
800 debug_return_int(rval);