Merge commit 'upstream/1.8.1p2'
[debian/sudo] / src / exec.c
1 /*
2  * Copyright (c) 2009-2011 Todd C. Miller <Todd.Miller@courtesan.com>
3  *
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.
7  *
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.
15  */
16
17 #include <config.h>
18
19 #include <sys/types.h>
20 #include <sys/param.h>
21 #ifdef HAVE_SYS_SYSMACROS_H
22 # include <sys/sysmacros.h>
23 #endif
24 #include <sys/socket.h>
25 #include <sys/stat.h>
26 #include <sys/time.h>
27 #include <sys/wait.h>
28 #include <sys/ioctl.h>
29 #ifdef HAVE_SYS_SELECT_H
30 # include <sys/select.h>
31 #endif /* HAVE_SYS_SELECT_H */
32 #include <stdio.h>
33 #ifdef STDC_HEADERS
34 # include <stdlib.h>
35 # include <stddef.h>
36 #else
37 # ifdef HAVE_STDLIB_H
38 #  include <stdlib.h>
39 # endif
40 #endif /* STDC_HEADERS */
41 #ifdef HAVE_STRING_H
42 # include <string.h>
43 #endif /* HAVE_STRING_H */
44 #ifdef HAVE_STRINGS_H
45 # include <strings.h>
46 #endif /* HAVE_STRINGS_H */
47 #ifdef HAVE_UNISTD_H
48 # include <unistd.h>
49 #endif /* HAVE_UNISTD_H */
50 #if TIME_WITH_SYS_TIME
51 # include <time.h>
52 #endif
53 #ifdef HAVE_SETLOCALE
54 # include <locale.h>
55 #endif
56 #include <errno.h>
57 #include <fcntl.h>
58 #include <signal.h>
59 #include <termios.h>
60
61 #include "sudo.h"
62 #include "sudo_exec.h"
63 #include "sudo_plugin.h"
64 #include "sudo_plugin_int.h"
65
66 /* Shared with exec_pty.c for use with handler(). */
67 int signal_pipe[2];
68
69 /* We keep a tailq of signals to forward to child. */
70 struct sigforward {
71     struct sigforward *prev, *next;
72     int signo;
73 };
74 TQ_DECLARE(sigforward)
75 static struct sigforward_list sigfwd_list;
76
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);
81
82 /*
83  * Like execve(2) but falls back to running through /bin/sh
84  * ala execvp(3) if we get ENOEXEC.
85  */
86 int
87 my_execve(const char *path, char *const argv[], char *const envp[])
88 {
89     execve(path, argv, envp);
90     if (errno == ENOEXEC) {
91         int argc;
92         char **nargv;
93
94         for (argc = 0; argv[argc] != NULL; argc++)
95             continue;
96         nargv = emalloc2(argc + 2, sizeof(char *));
97         nargv[0] = "sh";
98         nargv[1] = (char *)path;
99         memcpy(nargv + 2, argv + 1, argc * sizeof(char *));
100         execve(_PATH_BSHELL, nargv, envp);
101         efree(nargv);
102     }
103     return -1;
104 }
105
106 /*
107  * Fork and execute a command, returns the child's pid.
108  * Sends errno back on sv[1] if execve() fails.
109  */
110 static int fork_cmnd(struct command_details *details, int sv[2])
111 {
112     struct command_status cstat;
113     sigaction_t sa;
114     pid_t child;
115
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);
121
122     child = fork();
123     switch (child) {
124     case -1:
125         error(1, "fork");
126         break;
127     case 0:
128         /* child */
129         close(sv[0]);
130         close(signal_pipe[0]);
131         close(signal_pipe[1]);
132         fcntl(sv[1], F_SETFD, FD_CLOEXEC);
133         restore_signals();
134         if (exec_setup(details, NULL, -1) == TRUE) {
135             /* headed for execve() */
136             if (details->closefrom >= 0)
137                 closefrom(details->closefrom);
138 #ifdef HAVE_SELINUX
139             if (ISSET(details->flags, CD_RBAC_ENABLED))
140                 selinux_execve(details->command, details->argv, details->envp);
141             else
142 #endif
143                 my_execve(details->command, details->argv, details->envp);
144         }
145         cstat.type = CMD_ERRNO;
146         cstat.val = errno;
147         send(sv[1], &cstat, sizeof(cstat), 0);
148         _exit(1);
149     }
150     return child;
151 }
152
153 static struct signal_state {
154     int signo;
155     sigaction_t sa;
156 } saved_signals[] = {
157     { SIGALRM },
158     { SIGCHLD },
159     { SIGCONT },
160     { SIGHUP },
161     { SIGINT },
162     { SIGPIPE },
163     { SIGQUIT },
164     { SIGTERM },
165     { SIGTSTP },
166     { SIGTTIN },
167     { SIGTTOU },
168     { SIGUSR1 },
169     { SIGUSR2 },
170     { -1 }
171 };
172
173 /*
174  * Save signal handler state so it can be restored before exec.
175  */
176 void
177 save_signals(void)
178 {
179     struct signal_state *ss;
180
181     for (ss = saved_signals; ss->signo != -1; ss++)
182         sigaction(ss->signo, NULL, &ss->sa);
183 }
184
185 /*
186  * Restore signal handlers to initial state.
187  */
188 void
189 restore_signals(void)
190 {
191     struct signal_state *ss;
192
193     for (ss = saved_signals; ss->signo != -1; ss++)
194         sigaction(ss->signo, &ss->sa, NULL);
195 }
196
197 /*
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.
201  */
202 int
203 sudo_execve(struct command_details *details, struct command_status *cstat)
204 {
205     int maxfd, n, nready, sv[2], log_io = FALSE;
206     const char *utmp_user = NULL;
207     fd_set *fdsr, *fdsw;
208     sigaction_t sa;
209     pid_t child;
210
211     /* If running in background mode, fork and exit. */
212     if (ISSET(details->flags, CD_BACKGROUND)) {
213         switch (fork()) {
214             case -1:
215                 cstat->type = CMD_ERRNO;
216                 cstat->val = errno;
217                 return -1;
218             case 0:
219                 /* child continues */   
220                 break;
221             default:
222                 /* parent exits */
223                 exit(0);
224         }
225     }
226
227     /*
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.
231      */
232     if (!tq_empty(&io_plugins) || ISSET(details->flags, CD_USE_PTY)) {
233         log_io = TRUE;
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);
239         }
240     }
241
242     /*
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.
245      */
246     if (socketpair(PF_UNIX, SOCK_DGRAM, 0, sv) == -1)
247         error(1, "cannot create sockets");
248
249     /*
250      * We use a pipe to atomically handle signal notification within
251      * the select() loop.
252      */
253     if (pipe_nonblock(signal_pipe) != 0)
254         error(1, "cannot create pipe");
255
256     zero_bytes(&sa, sizeof(sa));
257     sigemptyset(&sa.sa_mask);
258
259     /*
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.
262      */
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);
274
275     /* Max fd we will be selecting on. */
276     maxfd = MAX(sv[0], signal_pipe[0]);
277
278     /*
279      * Child will run the command in the pty, parent will pass data
280      * to and from pty.  Adjusts maxfd as needed.
281      */
282     if (log_io)
283         child = fork_pty(details, sv, &maxfd);
284     else
285         child = fork_cmnd(details, sv);
286     close(sv[1]);
287
288     /* Set command timeout if specified. */
289     if (ISSET(details->flags, CD_SET_TIMEOUT))
290         alarm(details->timeout);
291
292 #ifdef HAVE_SETLOCALE
293     /*
294      * I/O logging must be in the C locale for floating point numbers
295      * to be logged consistently.
296      */
297     setlocale(LC_ALL, "C");
298 #endif
299
300     /*
301      * In the event loop we pass input from user tty to master
302      * and pass output from master to stdout and IO plugin.
303      */
304     fdsr = (fd_set *)emalloc2(howmany(maxfd + 1, NFDBITS), sizeof(fd_mask));
305     fdsw = (fd_set *)emalloc2(howmany(maxfd + 1, NFDBITS), sizeof(fd_mask));
306     for (;;) {
307         zero_bytes(fdsw, howmany(maxfd + 1, NFDBITS) * sizeof(fd_mask));
308         zero_bytes(fdsr, howmany(maxfd + 1, NFDBITS) * sizeof(fd_mask));
309
310         FD_SET(signal_pipe[0], fdsr);
311         FD_SET(sv[0], fdsr);
312         if (!tq_empty(&sigfwd_list))
313             FD_SET(sv[0], fdsw);
314         if (log_io)
315             fd_set_iobs(fdsr, fdsw); /* XXX - better name */
316         nready = select(maxfd + 1, fdsr, fdsw, NULL, NULL);
317         if (nready == -1) {
318             if (errno == EINTR)
319                 continue;
320             error(1, "select failed");
321         }
322         if (FD_ISSET(sv[0], fdsw)) {
323             forward_signals(sv[0]);
324         }
325         if (FD_ISSET(signal_pipe[0], fdsr)) {
326             n = handle_signals(signal_pipe[0], child, log_io, cstat);
327             if (n == 0) {
328                 /* Child has exited, cstat is set, we are done. */
329                 goto done;
330             }
331             if (n == -1) {
332                 /* Error reading signal_pipe[0], should not happen. */
333                 break;
334             }
335             /* Restart event loop so signals get sent to child immediately. */
336             continue;
337         }
338         if (FD_ISSET(sv[0], fdsr)) {
339             /* read child status */
340             n = recv(sv[0], cstat, sizeof(*cstat), 0);
341             if (n == -1) {
342                 if (errno == EINTR)
343                     continue;
344                 /*
345                  * If not logging I/O we will receive ECONNRESET when
346                  * the command is executed.  It is safe to ignore this.
347                  */
348                 if (log_io && errno != EAGAIN) {
349                     cstat->type = CMD_ERRNO;
350                     cstat->val = errno;
351                     break;
352                 }
353             }
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));
359                     schedule_signal(n);
360                     continue;
361                 } else {
362                     /* Child exited or was killed, either way we are done. */
363                     break;
364                 }
365             } else if (cstat->type == CMD_ERRNO) {
366                 /* Child was unable to execute command or broken pipe. */
367                 break;
368             }
369         }
370
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]);
375             break;
376         }
377     }
378
379     if (log_io) {
380         /* Flush any remaining output and free pty-related memory. */
381         pty_close(cstat);
382    }
383
384 #ifdef HAVE_SELINUX
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");
389     }
390 #endif
391
392 done:
393     efree(fdsr);
394     efree(fdsw);
395     while (!tq_empty(&sigfwd_list)) {
396         struct sigforward *sigfwd = tq_first(&sigfwd_list);
397         tq_remove(&sigfwd_list, sigfwd);
398         efree(sigfwd);
399     }
400
401     return cstat->type == CMD_ERRNO ? -1 : 0;
402 }
403
404 /*
405  * Read signals on fd written to by handler().
406  * Returns -1 on error, 0 on child exit, else 1.
407  */
408 static int
409 handle_signals(int fd, pid_t child, int log_io, struct command_status *cstat)
410 {
411     unsigned char signo;
412     ssize_t nread;
413     int status;
414     pid_t pid;
415
416     for (;;) {
417         /* read signal pipe */
418         nread = read(signal_pipe[0], &signo, sizeof(signo));
419         if (nread <= 0) {
420             /* It should not be possible to get EOF but just in case. */
421             if (nread == 0)
422                 errno = ECONNRESET;
423             /* Restart if interrupted by signal so the pipe doesn't fill. */
424             if (errno == EINTR)
425                 continue;
426             /* If pipe is empty, we are done. */
427             if (errno == EAGAIN)
428                 break;
429             sudo_debug(9, "error reading signal pipe %s", strerror(errno));
430             cstat->type = CMD_ERRNO;
431             cstat->val = errno;
432             return -1;
433         }
434         sudo_debug(9, "received signal %d", signo);
435         if (signo == SIGCHLD) {
436             /*
437              * If logging I/O, child is the intermediate process,
438              * otherwise it is the command itself.
439              */
440             do {
441                 pid = waitpid(child, &status, WUNTRACED|WNOHANG);
442             } while (pid == -1 && errno == EINTR);
443             if (pid == child) {
444                 /* If not logging I/O and child has exited we are done. */
445                 if (!log_io) {
446                     if (WIFSTOPPED(status)) {
447                         /*
448                          * Save the controlling terminal's process group
449                          * so we can restore it after we resume.
450                          */
451                         pid_t saved_pgrp = (pid_t)-1;
452                         int fd = open(_PATH_TTY, O_RDWR|O_NOCTTY, 0);
453                         if (fd != -1)
454                             saved_pgrp = tcgetpgrp(fd);
455                         if (kill(getpid(), WSTOPSIG(status)) != 0)
456                             warning("kill(%d, %d)", getpid(), WSTOPSIG(status));
457                         if (fd != -1) {
458                             if (saved_pgrp != (pid_t)-1)
459                                 (void)tcsetpgrp(fd, saved_pgrp);
460                             close(fd);
461                         }
462                     } else {
463                         /* Child has exited, we are done. */
464                         cstat->type = CMD_WSTATUS;
465                         cstat->val = status;
466                         return 0;
467                     }
468                 }
469                 /* Else we get ECONNRESET on sv[0] if child dies. */
470             }
471         } else {
472             if (log_io) {
473                 /* Schedule signo to be forwared to the child. */
474                 schedule_signal(signo);
475             } else {
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);
481             }
482         }
483     }
484     return 1;
485 }
486
487 /*
488  * Forward signals in sigfwd_list to child listening on fd.
489  */
490 static void
491 forward_signals(int sock)
492 {
493     struct sigforward *sigfwd;
494     struct command_status cstat;
495     ssize_t nsent;
496
497     while (!tq_empty(&sigfwd_list)) {
498         sigfwd = tq_first(&sigfwd_list);
499         sudo_debug(9, "sending signal %d to child over backchannel",
500             sigfwd->signo);
501         cstat.type = CMD_SIGNO;
502         cstat.val = sigfwd->signo;
503         do {
504             nsent = send(sock, &cstat, sizeof(cstat), 0);
505         } while (nsent == -1 && errno == EINTR);
506         tq_remove(&sigfwd_list, sigfwd);
507         efree(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);
514                     efree(sigfwd);
515                 }
516             }
517             break;
518         }
519     }
520 }
521
522 /*
523  * Schedule a signal to be forwared.
524  */
525 static void
526 schedule_signal(int signo)
527 {
528     struct sigforward *sigfwd;
529
530     sigfwd = emalloc(sizeof(*sigfwd));
531     sigfwd->prev = sigfwd;
532     sigfwd->next = NULL;
533     sigfwd->signo = signo;
534     tq_append(&sigfwd_list, sigfwd);
535 }
536
537 /*
538  * Generic handler for signals passed from parent -> child.
539  * The other end of signal_pipe is checked in the main event loop.
540  */
541 void
542 handler(int s)
543 {
544     unsigned char signo = (unsigned char)s;
545
546     /*
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.
549      */
550     if (write(signal_pipe[1], &signo, sizeof(signo)) == -1)
551         /* shut up glibc */;
552 }
553
554 /*
555  * Open a pipe and make both ends non-blocking.
556  * Returns 0 on success and -1 on error.
557  */
558 int
559 pipe_nonblock(int fds[2])
560 {
561     int flags, rval;
562
563     rval = pipe(fds);
564     if (rval != -1) {
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);
568         if (rval != -1) {
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);
572         }
573         if (rval == -1) {
574             close(fds[0]);
575             close(fds[1]);
576         }
577     }
578
579     return rval;
580 }