19dbad2e4dca52f116c0a32406a9b37e11505af6
[debian/sudo] / exec.c
1 /*
2  * Copyright (c) 2009-2010 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 #ifdef HAVE_TERMIOS_H
29 # include <termios.h>
30 #else
31 # include <termio.h>
32 #endif /* HAVE_TERMIOS_H */
33 #include <sys/ioctl.h>
34 #ifdef HAVE_SYS_SELECT_H
35 # include <sys/select.h>
36 #endif /* HAVE_SYS_SELECT_H */
37 #include <stdio.h>
38 #ifdef STDC_HEADERS
39 # include <stdlib.h>
40 # include <stddef.h>
41 #else
42 # ifdef HAVE_STDLIB_H
43 #  include <stdlib.h>
44 # endif
45 #endif /* STDC_HEADERS */
46 #ifdef HAVE_STRING_H
47 # include <string.h>
48 #endif /* HAVE_STRING_H */
49 #ifdef HAVE_STRINGS_H
50 # include <strings.h>
51 #endif /* HAVE_STRINGS_H */
52 #ifdef HAVE_UNISTD_H
53 # include <unistd.h>
54 #endif /* HAVE_UNISTD_H */
55 #if TIME_WITH_SYS_TIME
56 # include <time.h>
57 #endif
58 #ifdef HAVE_SETLOCALE
59 # include <locale.h>
60 #endif
61 #include <errno.h>
62 #include <fcntl.h>
63 #include <signal.h>
64 #ifdef HAVE_SELINUX
65 # include <selinux/selinux.h>
66 #endif
67
68 #include "sudo.h"
69 #include "sudo_exec.h"
70
71 /* Shared with exec_pty.c for use with handler(). */
72 int signal_pipe[2];
73
74 #ifdef _PATH_SUDO_IO_LOGDIR
75 /* We keep a tailq of signals to forward to child. */
76 struct sigforward {
77     struct sigforward *prev, *next;
78     int signo;
79 };
80 TQ_DECLARE(sigforward)
81 static struct sigforward_list sigfwd_list;
82 static void forward_signals __P((int fd));
83 static void schedule_signal __P((int signo));
84 static int log_io;
85 #endif /* _PATH_SUDO_IO_LOGDIR */
86
87 static int handle_signals __P((int fd, pid_t child,
88     struct command_status *cstat));
89
90 /*
91  * Like execve(2) but falls back to running through /bin/sh
92  * ala execvp(3) if we get ENOEXEC.
93  */
94 int
95 my_execve(path, argv, envp)
96     const char *path;
97     char *argv[];
98     char *envp[];
99 {
100     execve(path, argv, envp);
101     if (errno == ENOEXEC) {
102         argv--;                 /* at least one extra slot... */
103         argv[0] = "sh";
104         argv[1] = (char *)path;
105         execve(_PATH_BSHELL, argv, envp);
106     }
107     return -1;
108 }
109
110 /*
111  * Fork and execute a command, returns the child's pid.
112  * Sends errno back on sv[1] if execve() fails.
113  */
114 static int fork_cmnd(path, argv, envp, sv, rbac_enabled)
115     const char *path;
116     char *argv[];
117     char *envp[];
118     int sv[2];
119     int rbac_enabled;
120 {
121     struct command_status cstat;
122     sigaction_t sa;
123     pid_t child;
124
125     zero_bytes(&sa, sizeof(sa));
126     sigemptyset(&sa.sa_mask);
127     sa.sa_flags = SA_INTERRUPT; /* do not restart syscalls */
128     sa.sa_handler = handler;
129     sigaction(SIGCONT, &sa, NULL);
130
131     child = fork();
132     switch (child) {
133     case -1:
134         error(1, "fork");
135         break;
136     case 0:
137         /* child */
138         close(sv[0]);
139         close(signal_pipe[0]);
140         close(signal_pipe[1]);
141         fcntl(sv[1], F_SETFD, FD_CLOEXEC);
142         restore_signals();
143         if (exec_setup(rbac_enabled, user_ttypath, -1) == TRUE) {
144             /* headed for execve() */
145             closefrom(def_closefrom);
146 #ifdef HAVE_SELINUX
147             if (rbac_enabled)
148                 selinux_execve(path, argv, envp);
149             else
150 #endif
151                 my_execve(path, argv, envp);
152         }
153         cstat.type = CMD_ERRNO;
154         cstat.val = errno;
155         send(sv[1], &cstat, sizeof(cstat), 0);
156         _exit(1);
157     }
158     return child;
159 }
160
161 static struct signal_state {
162     int signo;
163     sigaction_t sa;
164 } saved_signals[] = {
165     { SIGALRM },
166     { SIGCHLD },
167     { SIGCONT },
168     { SIGHUP },
169     { SIGINT },
170     { SIGPIPE },
171     { SIGQUIT },
172     { SIGTERM },
173     { SIGTSTP },
174     { SIGTTIN },
175     { SIGTTOU },
176     { SIGUSR1 },
177     { SIGUSR2 },
178     { -1 }
179 };
180
181 /*
182  * Save signal handler state so it can be restored before exec.
183  */
184 void
185 save_signals()
186 {
187     struct signal_state *ss;
188
189     for (ss = saved_signals; ss->signo != -1; ss++)
190         sigaction(ss->signo, NULL, &ss->sa);
191 }
192
193 /*
194  * Restore signal handlers to initial state.
195  */
196 void
197 restore_signals()
198 {
199     struct signal_state *ss;
200
201     for (ss = saved_signals; ss->signo != -1; ss++)
202         sigaction(ss->signo, &ss->sa, NULL);
203 }
204
205 /*
206  * Execute a command, potentially in a pty with I/O loggging.
207  * This is a little bit tricky due to how POSIX job control works and
208  * we fact that we have two different controlling terminals to deal with.
209  */
210 int
211 sudo_execve(path, argv, envp, uid, cstat, dowait, bgmode)
212     const char *path;
213     char *argv[];
214     char *envp[];
215     uid_t uid;
216     struct command_status *cstat;
217     int dowait;
218     int bgmode;
219 {
220     int maxfd, n, nready, sv[2];
221     int rbac_enabled = 0;
222     fd_set *fdsr, *fdsw;
223     sigaction_t sa;
224     pid_t child;
225
226     /* If running in background mode, fork and exit. */
227     if (bgmode) {
228         switch (fork()) {
229             case -1:
230                 cstat->type = CMD_ERRNO;
231                 cstat->val = errno;
232                 return -1;
233             case 0:
234                 /* child continues */   
235                 break;
236             default:
237                 /* parent exits */
238                 exit(0);
239         }
240     }
241
242 #ifdef _PATH_SUDO_IO_LOGDIR
243     log_io = def_log_output || def_log_input || def_use_pty;
244     if (log_io) {
245         if (!bgmode)
246             pty_setup(uid);
247         io_log_open();
248         dowait = TRUE;
249     }
250 #endif /* _PATH_SUDO_IO_LOGDIR */
251
252 #ifdef HAVE_SELINUX
253     rbac_enabled = is_selinux_enabled() > 0 && user_role != NULL;
254     if (rbac_enabled)
255         dowait = TRUE;
256 #endif
257
258     /*
259      * If we don't need to wait for the command to finish, just exec it.
260      */
261     if (!dowait) {
262         exec_setup(FALSE, NULL, -1);
263         closefrom(def_closefrom);
264         my_execve(path, argv, envp);
265         cstat->type = CMD_ERRNO;
266         cstat->val = errno;
267         return 127;
268     }
269
270     /*
271      * We communicate with the child over a bi-directional pair of sockets.
272      * Parent sends signal info to child and child sends back wait status.
273      */
274     if (socketpair(PF_UNIX, SOCK_DGRAM, 0, sv) == -1)
275         error(1, "cannot create sockets");
276
277     /*
278      * We use a pipe to atomically handle signal notification within
279      * the select() loop.
280      */
281     if (pipe_nonblock(signal_pipe) != 0)
282         error(1, "cannot create pipe");
283
284     zero_bytes(&sa, sizeof(sa));
285     sigemptyset(&sa.sa_mask);
286
287     /*
288      * Signals for forward to the child process (excluding SIGCHLD).
289      * Note: HP-UX select() will not be interrupted if SA_RESTART set.
290      */
291     sa.sa_flags = SA_INTERRUPT; /* do not restart syscalls */
292     sa.sa_handler = handler;
293     sigaction(SIGALRM, &sa, NULL);
294     sigaction(SIGCHLD, &sa, NULL);
295     sigaction(SIGHUP, &sa, NULL);
296     sigaction(SIGINT, &sa, NULL);
297     sigaction(SIGPIPE, &sa, NULL);
298     sigaction(SIGQUIT, &sa, NULL);
299     sigaction(SIGTERM, &sa, NULL);
300     sigaction(SIGUSR1, &sa, NULL);
301     sigaction(SIGUSR2, &sa, NULL);
302
303     /* Max fd we will be selecting on. */
304     maxfd = MAX(sv[0], signal_pipe[0]);
305
306     /*
307      * Child will run the command in the pty, parent will pass data
308      * to and from pty.  Adjusts maxfd as needed.
309      */
310 #ifdef _PATH_SUDO_IO_LOGDIR
311     if (log_io)
312         child = fork_pty(path, argv, envp, sv, rbac_enabled, &maxfd);
313     else
314 #endif
315         child = fork_cmnd(path, argv, envp, sv, rbac_enabled);
316     close(sv[1]);
317
318 #ifdef HAVE_SETLOCALE
319     /*
320      * I/O logging must be in the C locale for floating point numbers
321      * to be logged consistently.
322      */
323     setlocale(LC_ALL, "C");
324 #endif
325
326     /*
327      * In the event loop we pass input from user tty to master
328      * and pass output from master to stdout and IO plugin.
329      */
330     fdsr = (fd_set *)emalloc2(howmany(maxfd + 1, NFDBITS), sizeof(fd_mask));
331     fdsw = (fd_set *)emalloc2(howmany(maxfd + 1, NFDBITS), sizeof(fd_mask));
332     for (;;) {
333         zero_bytes(fdsw, howmany(maxfd + 1, NFDBITS) * sizeof(fd_mask));
334         zero_bytes(fdsr, howmany(maxfd + 1, NFDBITS) * sizeof(fd_mask));
335
336         FD_SET(signal_pipe[0], fdsr);
337         FD_SET(sv[0], fdsr);
338 #ifdef _PATH_SUDO_IO_LOGDIR
339         if (!tq_empty(&sigfwd_list))
340             FD_SET(sv[0], fdsw);
341         if (log_io)
342             fd_set_iobs(fdsr, fdsw); /* XXX - better name */
343 #endif
344         nready = select(maxfd + 1, fdsr, fdsw, NULL, NULL);
345         if (nready == -1) {
346             if (errno == EINTR)
347                 continue;
348             error(1, "select failed");
349         }
350 #ifdef _PATH_SUDO_IO_LOGDIR
351         if (FD_ISSET(sv[0], fdsw)) {
352             forward_signals(sv[0]);
353         }
354 #endif /* _PATH_SUDO_IO_LOGDIR */
355         if (FD_ISSET(signal_pipe[0], fdsr)) {
356             n = handle_signals(signal_pipe[0], child, cstat);
357             if (n == 0) {
358                 /* Child has exited, cstat is set, we are done. */
359                 goto done;
360             }
361             if (n == -1) {
362                 /* Error reading signal_pipe[0], should not happen. */
363                 break;
364             }
365             /* Restart event loop so signals get sent to child immediately. */
366             continue;
367         }
368         if (FD_ISSET(sv[0], fdsr)) {
369             /* read child status */
370             n = recv(sv[0], cstat, sizeof(*cstat), 0);
371             if (n == -1) {
372                 if (errno == EINTR)
373                     continue;
374 #ifdef _PATH_SUDO_IO_LOGDIR
375                 /*
376                  * If not logging I/O we will receive ECONNRESET when
377                  * the command is executed.  It is safe to ignore this.
378                  */
379                 if (log_io && errno != EAGAIN) {
380                     cstat->type = CMD_ERRNO;
381                     cstat->val = errno;
382                     break;
383                 }
384 #endif
385             }
386 #ifdef _PATH_SUDO_IO_LOGDIR /* XXX */
387             if (cstat->type == CMD_WSTATUS) {
388                 if (WIFSTOPPED(cstat->val)) {
389                     /* Suspend parent and tell child how to resume on return. */
390                     n = suspend_parent(WSTOPSIG(cstat->val));
391                     schedule_signal(n);
392                     continue;
393                 } else {
394                     /* Child exited or was killed, either way we are done. */
395                     break;
396                 }
397             } else
398 #endif /* _PATH_SUDO_IO_LOGDIR */
399             if (cstat->type == CMD_ERRNO) {
400                 /* Child was unable to execute command or broken pipe. */
401                 break;
402             }
403         }
404
405 #ifdef _PATH_SUDO_IO_LOGDIR
406         if (perform_io(fdsr, fdsw, cstat) != 0) {
407             /* I/O error, kill child if still alive and finish. */
408             schedule_signal(SIGKILL);
409             forward_signals(sv[0]);
410             break;
411         }
412 #endif /* _PATH_SUDO_IO_LOGDIR */
413     }
414
415 #ifdef _PATH_SUDO_IO_LOGDIR
416     if (log_io) {
417         /* Flush any remaining output and free pty-related memory. */
418         pty_close(cstat);
419     }
420 #endif /* _PATH_SUDO_IO_LOGDIR */
421
422 #ifdef HAVE_SELINUX
423     if (rbac_enabled) {
424         /* This is probably not needed in log_io mode. */
425         if (selinux_restore_tty() != 0)
426             warningx("unable to restore tty label");
427     }
428 #endif
429
430 done:
431     efree(fdsr);
432     efree(fdsw);
433 #ifdef _PATH_SUDO_IO_LOGDIR
434     while (!tq_empty(&sigfwd_list)) {
435         struct sigforward *sigfwd = tq_first(&sigfwd_list);
436         tq_remove(&sigfwd_list, sigfwd);
437         efree(sigfwd);
438     }
439 #endif /* _PATH_SUDO_IO_LOGDIR */
440
441     return cstat->type == CMD_ERRNO ? -1 : 0;
442 }
443
444 /*
445  * Read signals on fd written to by handler().
446  * Returns -1 on error, 0 on child exit, else 1.
447  */
448 static int
449 handle_signals(fd, child, cstat)
450     int fd;
451     pid_t child;
452     struct command_status *cstat;
453 {
454     unsigned char signo;
455     ssize_t nread;
456     int status;
457     pid_t pid;
458
459     for (;;) {
460         /* read signal pipe */
461         nread = read(signal_pipe[0], &signo, sizeof(signo));
462         if (nread <= 0) {
463             /* It should not be possible to get EOF but just in case. */
464             if (nread == 0)
465                 errno = ECONNRESET;
466             /* Restart if interrupted by signal so the pipe doesn't fill. */
467             if (errno == EINTR)
468                 continue;
469             /* If pipe is empty, we are done. */
470             if (errno == EAGAIN)
471                 break;
472             cstat->type = CMD_ERRNO;
473             cstat->val = errno;
474             return -1;
475         }
476         if (signo == SIGCHLD) {
477             /*
478              * If logging I/O, child is the intermediate process,
479              * otherwise it is the command itself.
480              */
481             do {
482 #ifdef sudo_waitpid
483                 pid = sudo_waitpid(child, &status, WUNTRACED|WNOHANG);
484 #else
485                 pid = wait(&status);
486 #endif
487             } while (pid == -1 && errno == EINTR);
488             if (pid == child) {
489                 /* If not logging I/O and child has exited we are done. */
490 #ifdef _PATH_SUDO_IO_LOGDIR
491                 if (!log_io)
492 #endif
493                 {
494                     if (WIFSTOPPED(status)) {
495                         /*
496                          * Save the controlling terminal's process group
497                          * so we can restore it after we resume.
498                          */
499 #ifdef HAVE_TCSETPGRP
500                         pid_t saved_pgrp = (pid_t)-1;
501                         int fd = open(_PATH_TTY, O_RDWR|O_NOCTTY, 0);
502                         if (fd != -1)
503                             saved_pgrp = tcgetpgrp(fd);
504 #endif /* HAVE_TCSETPGRP */
505                         if (kill(getpid(), WSTOPSIG(status)) != 0)
506                             warning("kill(%d, %d)", getpid(), WSTOPSIG(status));
507 #ifdef HAVE_TCSETPGRP
508                         if (fd != -1) {
509                             if (saved_pgrp != (pid_t)-1)
510                                 (void)tcsetpgrp(fd, saved_pgrp);
511                             close(fd);
512                         }
513 #endif /* HAVE_TCSETPGRP */
514                     } else {
515                         /* Child has exited, we are done. */
516                         cstat->type = CMD_WSTATUS;
517                         cstat->val = status;
518                         return 0;
519                     }
520                 }
521                 /* Else we get ECONNRESET on sv[0] if child dies. */
522             }
523         } else {
524 #ifdef _PATH_SUDO_IO_LOGDIR
525             if (log_io) {
526                 /* Schedule signo to be forwared to the child. */
527                 schedule_signal(signo);
528             } else
529 #endif
530             {
531                 /* Nothing listening on sv[0], send directly. */
532                 if (kill(child, signo) != 0)
533                     warning("kill(%d, %d)", child, signo);
534             }
535         }
536     }
537     return 1;
538 }
539
540 #ifdef _PATH_SUDO_IO_LOGDIR
541 /*
542  * Forward signals in sigfwd_list to child listening on fd.
543  */
544 static void
545 forward_signals(sock)
546     int sock;
547 {
548     struct sigforward *sigfwd;
549     struct command_status cstat;
550     ssize_t nsent;
551
552     while (!tq_empty(&sigfwd_list)) {
553         sigfwd = tq_first(&sigfwd_list);
554         cstat.type = CMD_SIGNO;
555         cstat.val = sigfwd->signo;
556         do {
557             nsent = send(sock, &cstat, sizeof(cstat), 0);
558         } while (nsent == -1 && errno == EINTR);
559         tq_remove(&sigfwd_list, sigfwd);
560         efree(sigfwd);
561         if (nsent != sizeof(cstat)) {
562             if (errno == EPIPE) {
563                 /* Other end of socket gone, empty out sigfwd_list. */
564                 while (!tq_empty(&sigfwd_list)) {
565                     sigfwd = tq_first(&sigfwd_list);
566                     tq_remove(&sigfwd_list, sigfwd);
567                     efree(sigfwd);
568                 }
569             }
570             break;
571         }
572     }
573 }
574
575 /*
576  * Schedule a signal to be forwared.
577  */
578 static void
579 schedule_signal(signo)
580     int signo;
581 {
582     struct sigforward *sigfwd;
583
584     sigfwd = emalloc(sizeof(*sigfwd));
585     sigfwd->prev = sigfwd;
586     sigfwd->next = NULL;
587     sigfwd->signo = signo;
588     tq_append(&sigfwd_list, sigfwd);
589 }
590 #endif /* _PATH_SUDO_IO_LOGDIR */
591
592 /*
593  * Generic handler for signals passed from parent -> child.
594  * The other end of signal_pipe is checked in the main event loop.
595  */
596 RETSIGTYPE
597 handler(s)
598     int s;
599 {
600     unsigned char signo = (unsigned char)s;
601
602     /*
603      * The pipe is non-blocking, if we overflow the kernel's pipe
604      * buffer we drop the signal.  This is not a problem in practice.
605      */
606     if (write(signal_pipe[1], &signo, sizeof(signo)) == -1)
607         /* shut up glibc */;
608 }
609
610 /*
611  * Open a pipe and make both ends non-blocking.
612  * Returns 0 on success and -1 on error.
613  */
614 int
615 pipe_nonblock(fds)
616     int fds[2];
617 {
618     int flags, rval;
619
620     rval = pipe(fds);
621     if (rval != -1) {
622         flags = fcntl(fds[0], F_GETFL, 0);
623         if (flags != -1 && !ISSET(flags, O_NONBLOCK))
624             rval = fcntl(fds[0], F_SETFL, flags | O_NONBLOCK);
625         if (rval != -1) {
626             flags = fcntl(fds[1], F_GETFL, 0);
627             if (flags != -1 && !ISSET(flags, O_NONBLOCK))
628                 rval = fcntl(fds[1], F_SETFL, flags | O_NONBLOCK);
629         }
630         if (rval == -1) {
631             close(fds[0]);
632             close(fds[1]);
633         }
634     }
635
636     return rval;
637 }