2 * Copyright (c) 2009-2011 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 #include <sys/param.h>
21 #ifdef HAVE_SYS_SYSMACROS_H
22 # include <sys/sysmacros.h>
24 #include <sys/socket.h>
28 #include <sys/ioctl.h>
29 #ifdef HAVE_SYS_SELECT_H
30 # include <sys/select.h>
31 #endif /* HAVE_SYS_SELECT_H */
40 #endif /* STDC_HEADERS */
43 #endif /* HAVE_STRING_H */
46 #endif /* HAVE_STRINGS_H */
49 #endif /* HAVE_UNISTD_H */
50 #if TIME_WITH_SYS_TIME
62 #include "sudo_exec.h"
63 #include "sudo_plugin.h"
64 #include "sudo_plugin_int.h"
66 /* Shared with exec_pty.c for use with handler(). */
69 /* We keep a tailq of signals to forward to child. */
71 struct sigforward *prev, *next;
74 TQ_DECLARE(sigforward)
75 static struct sigforward_list sigfwd_list;
77 static int handle_signals(int fd, pid_t child, int log_io,
78 struct command_status *cstat);
79 static void forward_signals(int fd);
80 static void schedule_signal(int signo);
83 * Like execve(2) but falls back to running through /bin/sh
84 * ala execvp(3) if we get ENOEXEC.
87 my_execve(const char *path, char *const argv[], char *const envp[])
89 execve(path, argv, envp);
90 if (errno == ENOEXEC) {
94 for (argc = 0; argv[argc] != NULL; argc++)
96 nargv = emalloc2(argc + 2, sizeof(char *));
98 nargv[1] = (char *)path;
99 memcpy(nargv + 2, argv + 1, argc * sizeof(char *));
100 execve(_PATH_BSHELL, nargv, envp);
107 * Fork and execute a command, returns the child's pid.
108 * Sends errno back on sv[1] if execve() fails.
110 static int fork_cmnd(struct command_details *details, int sv[2])
112 struct command_status cstat;
116 zero_bytes(&sa, sizeof(sa));
117 sigemptyset(&sa.sa_mask);
118 sa.sa_flags = SA_INTERRUPT; /* do not restart syscalls */
119 sa.sa_handler = handler;
120 sigaction(SIGCONT, &sa, NULL);
130 close(signal_pipe[0]);
131 close(signal_pipe[1]);
132 fcntl(sv[1], F_SETFD, FD_CLOEXEC);
134 if (exec_setup(details, NULL, -1) == TRUE) {
135 /* headed for execve() */
136 if (details->closefrom >= 0)
137 closefrom(details->closefrom);
139 if (ISSET(details->flags, CD_RBAC_ENABLED))
140 selinux_execve(details->command, details->argv, details->envp);
143 my_execve(details->command, details->argv, details->envp);
145 cstat.type = CMD_ERRNO;
147 send(sv[1], &cstat, sizeof(cstat), 0);
153 static struct signal_state {
156 } saved_signals[] = {
174 * Save signal handler state so it can be restored before exec.
179 struct signal_state *ss;
181 for (ss = saved_signals; ss->signo != -1; ss++)
182 sigaction(ss->signo, NULL, &ss->sa);
186 * Restore signal handlers to initial state.
189 restore_signals(void)
191 struct signal_state *ss;
193 for (ss = saved_signals; ss->signo != -1; ss++)
194 sigaction(ss->signo, &ss->sa, NULL);
198 * Execute a command, potentially in a pty with I/O loggging.
199 * This is a little bit tricky due to how POSIX job control works and
200 * we fact that we have two different controlling terminals to deal with.
203 sudo_execve(struct command_details *details, struct command_status *cstat)
205 int maxfd, n, nready, sv[2], log_io = FALSE;
206 const char *utmp_user = NULL;
211 /* If running in background mode, fork and exit. */
212 if (ISSET(details->flags, CD_BACKGROUND)) {
215 cstat->type = CMD_ERRNO;
219 /* child continues */
228 * If we have an I/O plugin or the policy plugin has requested one, we
229 * need to allocate a pty. It is OK to set log_io in the pty-only case
230 * as the tailqueue plugin will be empty and no I/O logging will occur.
232 if (!tq_empty(&io_plugins) || ISSET(details->flags, CD_USE_PTY)) {
234 if (!ISSET(details->flags, CD_BACKGROUND)) {
235 if (ISSET(details->flags, CD_SET_UTMP))
236 utmp_user = details->utmp_user ? details->utmp_user : user_details.username;
237 sudo_debug(8, "allocate pty for I/O logging");
238 pty_setup(details->euid, user_details.tty, utmp_user);
243 * We communicate with the child over a bi-directional pair of sockets.
244 * Parent sends signal info to child and child sends back wait status.
246 if (socketpair(PF_UNIX, SOCK_DGRAM, 0, sv) == -1)
247 error(1, "cannot create sockets");
250 * We use a pipe to atomically handle signal notification within
253 if (pipe_nonblock(signal_pipe) != 0)
254 error(1, "cannot create pipe");
256 zero_bytes(&sa, sizeof(sa));
257 sigemptyset(&sa.sa_mask);
260 * Signals for forward to the child process (excluding SIGALRM and SIGCHLD).
261 * Note: HP-UX select() will not be interrupted if SA_RESTART set.
263 sa.sa_flags = SA_INTERRUPT; /* do not restart syscalls */
264 sa.sa_handler = handler;
265 sigaction(SIGALRM, &sa, NULL);
266 sigaction(SIGCHLD, &sa, NULL);
267 sigaction(SIGHUP, &sa, NULL);
268 sigaction(SIGINT, &sa, NULL);
269 sigaction(SIGPIPE, &sa, NULL);
270 sigaction(SIGQUIT, &sa, NULL);
271 sigaction(SIGTERM, &sa, NULL);
272 sigaction(SIGUSR1, &sa, NULL);
273 sigaction(SIGUSR2, &sa, NULL);
275 /* Max fd we will be selecting on. */
276 maxfd = MAX(sv[0], signal_pipe[0]);
279 * Child will run the command in the pty, parent will pass data
280 * to and from pty. Adjusts maxfd as needed.
283 child = fork_pty(details, sv, &maxfd);
285 child = fork_cmnd(details, sv);
288 /* Set command timeout if specified. */
289 if (ISSET(details->flags, CD_SET_TIMEOUT))
290 alarm(details->timeout);
292 #ifdef HAVE_SETLOCALE
294 * I/O logging must be in the C locale for floating point numbers
295 * to be logged consistently.
297 setlocale(LC_ALL, "C");
301 * In the event loop we pass input from user tty to master
302 * and pass output from master to stdout and IO plugin.
304 fdsr = (fd_set *)emalloc2(howmany(maxfd + 1, NFDBITS), sizeof(fd_mask));
305 fdsw = (fd_set *)emalloc2(howmany(maxfd + 1, NFDBITS), sizeof(fd_mask));
307 zero_bytes(fdsw, howmany(maxfd + 1, NFDBITS) * sizeof(fd_mask));
308 zero_bytes(fdsr, howmany(maxfd + 1, NFDBITS) * sizeof(fd_mask));
310 FD_SET(signal_pipe[0], fdsr);
312 if (!tq_empty(&sigfwd_list))
315 fd_set_iobs(fdsr, fdsw); /* XXX - better name */
316 nready = select(maxfd + 1, fdsr, fdsw, NULL, NULL);
320 error(1, "select failed");
322 if (FD_ISSET(sv[0], fdsw)) {
323 forward_signals(sv[0]);
325 if (FD_ISSET(signal_pipe[0], fdsr)) {
326 n = handle_signals(signal_pipe[0], child, log_io, cstat);
328 /* Child has exited, cstat is set, we are done. */
332 /* Error reading signal_pipe[0], should not happen. */
335 /* Restart event loop so signals get sent to child immediately. */
338 if (FD_ISSET(sv[0], fdsr)) {
339 /* read child status */
340 n = recv(sv[0], cstat, sizeof(*cstat), 0);
345 * If not logging I/O we will receive ECONNRESET when
346 * the command is executed. It is safe to ignore this.
348 if (log_io && errno != EAGAIN) {
349 cstat->type = CMD_ERRNO;
354 if (cstat->type == CMD_WSTATUS) {
355 if (WIFSTOPPED(cstat->val)) {
356 /* Suspend parent and tell child how to resume on return. */
357 sudo_debug(8, "child stopped, suspending parent");
358 n = suspend_parent(WSTOPSIG(cstat->val));
362 /* Child exited or was killed, either way we are done. */
365 } else if (cstat->type == CMD_ERRNO) {
366 /* Child was unable to execute command or broken pipe. */
371 if (perform_io(fdsr, fdsw, cstat) != 0) {
372 /* I/O error, kill child if still alive and finish. */
373 schedule_signal(SIGKILL);
374 forward_signals(sv[0]);
380 /* Flush any remaining output and free pty-related memory. */
385 if (ISSET(details->flags, CD_RBAC_ENABLED)) {
386 /* This is probably not needed in log_io mode. */
387 if (selinux_restore_tty() != 0)
388 warningx("unable to restore tty label");
395 while (!tq_empty(&sigfwd_list)) {
396 struct sigforward *sigfwd = tq_first(&sigfwd_list);
397 tq_remove(&sigfwd_list, sigfwd);
401 return cstat->type == CMD_ERRNO ? -1 : 0;
405 * Read signals on fd written to by handler().
406 * Returns -1 on error, 0 on child exit, else 1.
409 handle_signals(int fd, pid_t child, int log_io, struct command_status *cstat)
417 /* read signal pipe */
418 nread = read(signal_pipe[0], &signo, sizeof(signo));
420 /* It should not be possible to get EOF but just in case. */
423 /* Restart if interrupted by signal so the pipe doesn't fill. */
426 /* If pipe is empty, we are done. */
429 sudo_debug(9, "error reading signal pipe %s", strerror(errno));
430 cstat->type = CMD_ERRNO;
434 sudo_debug(9, "received signal %d", signo);
435 if (signo == SIGCHLD) {
437 * If logging I/O, child is the intermediate process,
438 * otherwise it is the command itself.
441 pid = waitpid(child, &status, WUNTRACED|WNOHANG);
442 } while (pid == -1 && errno == EINTR);
444 /* If not logging I/O and child has exited we are done. */
446 if (WIFSTOPPED(status)) {
448 * Save the controlling terminal's process group
449 * so we can restore it after we resume.
451 pid_t saved_pgrp = (pid_t)-1;
452 int fd = open(_PATH_TTY, O_RDWR|O_NOCTTY, 0);
454 saved_pgrp = tcgetpgrp(fd);
455 if (kill(getpid(), WSTOPSIG(status)) != 0)
456 warning("kill(%d, %d)", getpid(), WSTOPSIG(status));
458 if (saved_pgrp != (pid_t)-1)
459 (void)tcsetpgrp(fd, saved_pgrp);
463 /* Child has exited, we are done. */
464 cstat->type = CMD_WSTATUS;
469 /* Else we get ECONNRESET on sv[0] if child dies. */
473 /* Schedule signo to be forwared to the child. */
474 schedule_signal(signo);
476 /* Nothing listening on sv[0], send directly. */
477 if (signo == SIGALRM)
478 terminate_child(child, FALSE);
479 else if (kill(child, signo) != 0)
480 warning("kill(%d, %d)", child, signo);
488 * Forward signals in sigfwd_list to child listening on fd.
491 forward_signals(int sock)
493 struct sigforward *sigfwd;
494 struct command_status cstat;
497 while (!tq_empty(&sigfwd_list)) {
498 sigfwd = tq_first(&sigfwd_list);
499 sudo_debug(9, "sending signal %d to child over backchannel",
501 cstat.type = CMD_SIGNO;
502 cstat.val = sigfwd->signo;
504 nsent = send(sock, &cstat, sizeof(cstat), 0);
505 } while (nsent == -1 && errno == EINTR);
506 tq_remove(&sigfwd_list, sigfwd);
508 if (nsent != sizeof(cstat)) {
509 if (errno == EPIPE) {
510 /* Other end of socket gone, empty out sigfwd_list. */
511 while (!tq_empty(&sigfwd_list)) {
512 sigfwd = tq_first(&sigfwd_list);
513 tq_remove(&sigfwd_list, sigfwd);
523 * Schedule a signal to be forwared.
526 schedule_signal(int signo)
528 struct sigforward *sigfwd;
530 sigfwd = emalloc(sizeof(*sigfwd));
531 sigfwd->prev = sigfwd;
533 sigfwd->signo = signo;
534 tq_append(&sigfwd_list, sigfwd);
538 * Generic handler for signals passed from parent -> child.
539 * The other end of signal_pipe is checked in the main event loop.
544 unsigned char signo = (unsigned char)s;
547 * The pipe is non-blocking, if we overflow the kernel's pipe
548 * buffer we drop the signal. This is not a problem in practice.
550 if (write(signal_pipe[1], &signo, sizeof(signo)) == -1)
555 * Open a pipe and make both ends non-blocking.
556 * Returns 0 on success and -1 on error.
559 pipe_nonblock(int fds[2])
565 flags = fcntl(fds[0], F_GETFL, 0);
566 if (flags != -1 && !ISSET(flags, O_NONBLOCK))
567 rval = fcntl(fds[0], F_SETFL, flags | O_NONBLOCK);
569 flags = fcntl(fds[1], F_GETFL, 0);
570 if (flags != -1 && !ISSET(flags, O_NONBLOCK))
571 rval = fcntl(fds[1], F_SETFL, flags | O_NONBLOCK);