Imported Upstream version 1.8.4p4
[debian/sudo] / plugins / sudoers / sudoreplay.c
1 /*
2  * Copyright (c) 2009-2012 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/stat.h>
25 #include <sys/time.h>
26 #include <sys/wait.h>
27 #include <sys/ioctl.h>
28 #ifdef HAVE_SYS_SELECT_H
29 #include <sys/select.h>
30 #endif /* HAVE_SYS_SELECT_H */
31 #include <stdio.h>
32 #ifdef STDC_HEADERS
33 # include <stdlib.h>
34 # include <stddef.h>
35 #else
36 # ifdef HAVE_STDLIB_H
37 #  include <stdlib.h>
38 # endif
39 #endif /* STDC_HEADERS */
40 #ifdef HAVE_STRING_H
41 # if defined(HAVE_MEMORY_H) && !defined(STDC_HEADERS)
42 #  include <memory.h>
43 # endif
44 # include <string.h>
45 #endif /* HAVE_STRING_H */
46 #ifdef HAVE_STRINGS_H
47 # include <strings.h>
48 #endif /* HAVE_STRINGS_H */
49 #ifdef HAVE_UNISTD_H
50 # include <unistd.h>
51 #endif /* HAVE_UNISTD_H */
52 #if TIME_WITH_SYS_TIME
53 # include <time.h>
54 #endif
55 #ifndef HAVE_STRUCT_TIMESPEC
56 # include "compat/timespec.h"
57 #endif
58 #include <ctype.h>
59 #include <errno.h>
60 #include <limits.h>
61 #include <fcntl.h>
62 #ifdef HAVE_DIRENT_H
63 # include <dirent.h>
64 # define NAMLEN(dirent) strlen((dirent)->d_name)
65 #else
66 # define dirent direct
67 # define NAMLEN(dirent) (dirent)->d_namlen
68 # ifdef HAVE_SYS_NDIR_H
69 #  include <sys/ndir.h>
70 # endif
71 # ifdef HAVE_SYS_DIR_H
72 #  include <sys/dir.h>
73 # endif
74 # ifdef HAVE_NDIR_H
75 #  include <ndir.h>
76 # endif
77 #endif
78 #ifdef HAVE_REGCOMP
79 # include <regex.h>
80 #endif
81 #ifdef HAVE_ZLIB_H
82 # include <zlib.h>
83 #endif
84 #ifdef HAVE_SETLOCALE
85 # include <locale.h>
86 #endif
87 #include <signal.h>
88 #ifdef HAVE_STDBOOL_H
89 # include <stdbool.h>
90 #else
91 # include "compat/stdbool.h"
92 #endif /* HAVE_STDBOOL_H */
93
94 #include <pathnames.h>
95
96 #include "missing.h"
97 #include "alloc.h"
98 #include "error.h"
99 #include "gettext.h"
100 #include "sudo_plugin.h"
101 #include "sudo_conf.h"
102 #include "sudo_debug.h"
103
104 #ifndef LINE_MAX
105 # define LINE_MAX 2048
106 #endif
107
108 /* Must match the defines in iolog.c */
109 #define IOFD_STDIN      0
110 #define IOFD_STDOUT     1
111 #define IOFD_STDERR     2
112 #define IOFD_TTYIN      3
113 #define IOFD_TTYOUT     4
114 #define IOFD_TIMING     5
115 #define IOFD_MAX        6
116
117 /* Bitmap of iofds to be replayed */
118 unsigned int replay_filter = (1 << IOFD_STDOUT) | (1 << IOFD_STDERR) |
119                              (1 << IOFD_TTYOUT);
120
121 /* For getopt(3) */
122 extern char *optarg;
123 extern int optind;
124
125 union io_fd {
126     FILE *f;
127 #ifdef HAVE_ZLIB_H
128     gzFile g;
129 #endif
130     void *v;
131 };
132
133 /*
134  * Info present in the I/O log file
135  */
136 struct log_info {
137     char *cwd;
138     char *user;
139     char *runas_user;
140     char *runas_group;
141     char *tty;
142     char *cmd;
143     time_t tstamp;
144 };
145
146 /*
147  * Handle expressions like:
148  * ( user millert or user root ) and tty console and command /bin/sh
149  */
150 struct search_node {
151     struct search_node *next;
152 #define ST_EXPR         1
153 #define ST_TTY          2
154 #define ST_USER         3
155 #define ST_PATTERN      4
156 #define ST_RUNASUSER    5
157 #define ST_RUNASGROUP   6
158 #define ST_FROMDATE     7
159 #define ST_TODATE       8
160 #define ST_CWD          9
161     char type;
162     char negated;
163     char or;
164     char pad;
165     union {
166 #ifdef HAVE_REGCOMP
167         regex_t cmdre;
168 #endif
169         time_t tstamp;
170         char *cwd;
171         char *tty;
172         char *user;
173         char *pattern;
174         char *runas_group;
175         char *runas_user;
176         struct search_node *expr;
177         void *ptr;
178     } u;
179 } *search_expr;
180
181 sudo_conv_t sudo_conv;  /* NULL in non-plugin */
182
183 #define STACK_NODE_SIZE 32
184 static struct search_node *node_stack[32];
185 static int stack_top;
186
187 static const char *session_dir = _PATH_SUDO_IO_LOGDIR;
188
189 static union io_fd io_fds[IOFD_MAX];
190 static const char *io_fnames[IOFD_MAX] = {
191     "/stdin",
192     "/stdout",
193     "/stderr",
194     "/ttyin",
195     "/ttyout",
196     "/timing"
197 };
198
199 extern time_t get_date(char *);
200 extern char *get_timestr(time_t, int);
201 extern int term_raw(int, int);
202 extern int term_restore(int, int);
203 extern void zero_bytes(volatile void *, size_t);
204 void cleanup(int);
205
206 static int list_sessions(int, char **, const char *, const char *, const char *);
207 static int parse_expr(struct search_node **, char **);
208 static void check_input(int, double *);
209 static void delay(double);
210 static void help(void) __attribute__((__noreturn__));
211 static void usage(int);
212 static int open_io_fd(char *pathbuf, int len, const char *suffix, union io_fd *fdp);
213 static int parse_timing(const char *buf, const char *decimal, int *idx, double *seconds, size_t *nbytes);
214
215 #ifdef HAVE_REGCOMP
216 # define REGEX_T        regex_t
217 #else
218 # define REGEX_T        char
219 #endif
220
221 #define VALID_ID(s) (isalnum((unsigned char)(s)[0]) && \
222     isalnum((unsigned char)(s)[1]) && isalnum((unsigned char)(s)[2]) && \
223     isalnum((unsigned char)(s)[3]) && isalnum((unsigned char)(s)[4]) && \
224     isalnum((unsigned char)(s)[5]) && (s)[6] == '\0')
225
226 #define IS_IDLOG(s) ( \
227     isalnum((unsigned char)(s)[0]) && isalnum((unsigned char)(s)[1]) && \
228     (s)[2] == '/' && \
229     isalnum((unsigned char)(s)[3]) && isalnum((unsigned char)(s)[4]) && \
230     (s)[5] == '/' && \
231     isalnum((unsigned char)(s)[6]) && isalnum((unsigned char)(s)[7]) && \
232     (s)[8] == '/' && (s)[9] == 'l' && (s)[10] == 'o' && (s)[11] == 'g' && \
233     (s)[9] == '\0')
234
235 int
236 main(int argc, char *argv[])
237 {
238     int ch, idx, plen, nready, exitcode = 0, interactive = 0, listonly = 0;
239     const char *id, *user = NULL, *pattern = NULL, *tty = NULL, *decimal = ".";
240     char path[PATH_MAX], buf[LINE_MAX], *cp, *ep;
241     double seconds, to_wait, speed = 1.0, max_wait = 0;
242     FILE *lfile;
243     fd_set *fdsw;
244     sigaction_t sa;
245     size_t len, nbytes, nread, off;
246     ssize_t nwritten;
247     debug_decl(main, SUDO_DEBUG_MAIN)
248
249 #if defined(SUDO_DEVEL) && defined(__OpenBSD__)
250     {
251         extern char *malloc_options;
252         malloc_options = "AFGJPR";
253     }  
254 #endif
255
256 #if !defined(HAVE_GETPROGNAME) && !defined(HAVE___PROGNAME)
257     setprogname(argc > 0 ? argv[0] : "sudoreplay");
258 #endif
259
260 #ifdef HAVE_SETLOCALE
261     setlocale(LC_ALL, "");
262     decimal = localeconv()->decimal_point;
263 #endif
264     bindtextdomain("sudoers", LOCALEDIR); /* XXX - should have sudoreplay domain */
265     textdomain("sudoers");
266
267     /* Read sudo.conf. */
268     sudo_conf_read();
269
270     while ((ch = getopt(argc, argv, "d:f:hlm:s:V")) != -1) {
271         switch(ch) {
272         case 'd':
273             session_dir = optarg;
274             break;
275         case 'f':
276             /* Set the replay filter. */
277             replay_filter = 0;
278             for (cp = strtok(optarg, ","); cp; cp = strtok(NULL, ",")) {
279                 if (strcmp(cp, "stdout") == 0)
280                     SET(replay_filter, 1 << IOFD_STDOUT);
281                 else if (strcmp(cp, "stderr") == 0)
282                     SET(replay_filter, 1 << IOFD_STDERR);
283                 else if (strcmp(cp, "ttyout") == 0)
284                     SET(replay_filter, 1 << IOFD_TTYOUT);
285                 else
286                     errorx(1, _("invalid filter option: %s"), optarg);
287             }
288             break;
289         case 'h':
290             help();
291             /* NOTREACHED */
292         case 'l':
293             listonly = 1;
294             break;
295         case 'm':
296             errno = 0;
297             max_wait = strtod(optarg, &ep);
298             if (*ep != '\0' || errno != 0)
299                 errorx(1, _("invalid max wait: %s"), optarg);
300             break;
301         case 's':
302             errno = 0;
303             speed = strtod(optarg, &ep);
304             if (*ep != '\0' || errno != 0)
305                 errorx(1, _("invalid speed factor: %s"), optarg);
306             break;
307         case 'V':
308             (void) printf(_("%s version %s\n"), getprogname(), PACKAGE_VERSION);
309             goto done;
310         default:
311             usage(1);
312             /* NOTREACHED */
313         }
314
315     }
316     argc -= optind;
317     argv += optind;
318
319     if (listonly) {
320         exitcode = list_sessions(argc, argv, pattern, user, tty);
321         goto done;
322     }
323
324     if (argc != 1)
325         usage(1);
326
327     /* 6 digit ID in base 36, e.g. 01G712AB or free-form name */
328     id = argv[0];
329     if (VALID_ID(id)) {
330         plen = snprintf(path, sizeof(path), "%s/%.2s/%.2s/%.2s/timing",
331             session_dir, id, &id[2], &id[4]);
332         if (plen <= 0 || plen >= sizeof(path))
333             errorx(1, _("%s/%.2s/%.2s/%.2s/timing: %s"), session_dir,
334                 id, &id[2], &id[4], strerror(ENAMETOOLONG));
335     } else {
336         plen = snprintf(path, sizeof(path), "%s/%s/timing",
337             session_dir, id);
338         if (plen <= 0 || plen >= sizeof(path))
339             errorx(1, _("%s/%s/timing: %s"), session_dir,
340                 id, strerror(ENAMETOOLONG));
341     }
342     plen -= 7;
343
344     /* Open files for replay, applying replay filter for the -f flag. */
345     for (idx = 0; idx < IOFD_MAX; idx++) {
346         if (ISSET(replay_filter, 1 << idx) || idx == IOFD_TIMING) {
347             if (open_io_fd(path, plen, io_fnames[idx], &io_fds[idx]) == -1)
348                 error(1, _("unable to open %s"), path);
349         }
350     }
351
352     /* Read log file. */
353     path[plen] = '\0';
354     strlcat(path, "/log", sizeof(path));
355     lfile = fopen(path, "r");
356     if (lfile == NULL)
357         error(1, _("unable to open %s"), path);
358     cp = NULL;
359     len = 0;
360     /* Pull out command (third line). */
361     if (getline(&cp, &len, lfile) == -1 ||
362         getline(&cp, &len, lfile) == -1 ||
363         getline(&cp, &len, lfile) == -1) {
364         errorx(1, _("invalid log file %s"), path);
365     }
366     printf(_("Replaying sudo session: %s"), cp);
367     free(cp);
368     fclose(lfile);
369
370     fflush(stdout);
371     zero_bytes(&sa, sizeof(sa));
372     sigemptyset(&sa.sa_mask);
373     sa.sa_flags = SA_RESETHAND;
374     sa.sa_handler = cleanup;
375     (void) sigaction(SIGINT, &sa, NULL);
376     (void) sigaction(SIGKILL, &sa, NULL);
377     (void) sigaction(SIGTERM, &sa, NULL);
378     (void) sigaction(SIGHUP, &sa, NULL);
379     sa.sa_flags = SA_RESTART;
380     sa.sa_handler = SIG_IGN;
381     (void) sigaction(SIGTSTP, &sa, NULL);
382     (void) sigaction(SIGQUIT, &sa, NULL);
383
384     /* XXX - read user input from /dev/tty and set STDOUT to raw if not a pipe */
385     /* Set stdin to raw mode if it is a tty */
386     interactive = isatty(STDIN_FILENO);
387     if (interactive) {
388         ch = fcntl(STDIN_FILENO, F_GETFL, 0);
389         if (ch != -1)
390             (void) fcntl(STDIN_FILENO, F_SETFL, ch | O_NONBLOCK);
391         if (!term_raw(STDIN_FILENO, 1))
392             error(1, _("unable to set tty to raw mode"));
393     }
394     fdsw = (fd_set *)emalloc2(howmany(STDOUT_FILENO + 1, NFDBITS),
395         sizeof(fd_mask));
396
397     /*
398      * Timing file consists of line of the format: "%f %d\n"
399      */
400 #ifdef HAVE_ZLIB_H
401     while (gzgets(io_fds[IOFD_TIMING].g, buf, sizeof(buf)) != NULL) {
402 #else
403     while (fgets(buf, sizeof(buf), io_fds[IOFD_TIMING].f) != NULL) {
404 #endif
405         if (!parse_timing(buf, decimal, &idx, &seconds, &nbytes))
406             errorx(1, _("invalid timing file line: %s"), buf);
407
408         if (interactive)
409             check_input(STDIN_FILENO, &speed);
410
411         /* Adjust delay using speed factor and clamp to max_wait */
412         to_wait = seconds / speed;
413         if (max_wait && to_wait > max_wait)
414             to_wait = max_wait;
415         delay(to_wait);
416
417         /* Even if we are not relaying, we still have to delay. */
418         if (io_fds[idx].v == NULL)
419             continue;
420
421         /* All output is sent to stdout. */
422         while (nbytes != 0) {
423             if (nbytes > sizeof(buf))
424                 len = sizeof(buf);
425             else
426                 len = nbytes;
427 #ifdef HAVE_ZLIB_H
428             nread = gzread(io_fds[idx].g, buf, len);
429 #else
430             nread = fread(buf, 1, len, io_fds[idx].f);
431 #endif
432             nbytes -= nread;
433             off = 0;
434             do {
435                 /* no stdio, must be unbuffered */
436                 nwritten = write(STDOUT_FILENO, buf + off, nread - off);
437                 if (nwritten == -1) {
438                     if (errno == EINTR)
439                         continue;
440                     if (errno == EAGAIN) {
441                         FD_SET(STDOUT_FILENO, fdsw);
442                         do {
443                             nready = select(STDOUT_FILENO + 1, NULL, fdsw, NULL, NULL);
444                         } while (nready == -1 && errno == EINTR);
445                         if (nready == 1)
446                             continue;
447                     }
448                     error(1, _("writing to standard output"));
449                 }
450                 off += nwritten;
451             } while (nread > off);
452         }
453     }
454     term_restore(STDIN_FILENO, 1);
455 done:
456     sudo_debug_exit_int(__func__, __FILE__, __LINE__, sudo_debug_subsys, exitcode);
457     exit(exitcode);
458 }
459
460 static void
461 delay(double secs)
462 {
463     struct timespec ts, rts;
464     int rval;
465
466     /*
467      * Typical max resolution is 1/HZ but we can't portably check that.
468      * If the interval is small enough, just ignore it.
469      */
470     if (secs < 0.0001)
471         return;
472
473     rts.tv_sec = secs;
474     rts.tv_nsec = (secs - (double) rts.tv_sec) * 1000000000.0;
475     do {
476       memcpy(&ts, &rts, sizeof(ts));
477       rval = nanosleep(&ts, &rts);
478     } while (rval == -1 && errno == EINTR);
479     if (rval == -1) {
480         error2(1, _("nanosleep: tv_sec %ld, tv_nsec %ld"),
481             (long)ts.tv_sec, (long)ts.tv_nsec);
482     }
483 }
484
485 static int
486 open_io_fd(char *path, int len, const char *suffix, union io_fd *fdp)
487 {
488     path[len] = '\0';
489     strlcat(path, suffix, PATH_MAX);
490     debug_decl(open_io_fd, SUDO_DEBUG_UTIL)
491
492 #ifdef HAVE_ZLIB_H
493     fdp->g = gzopen(path, "r");
494 #else
495     fdp->f = fopen(path, "r");
496 #endif
497     debug_return_int(fdp->v ? 0 : -1);
498 }
499
500 /*
501  * Build expression list from search args
502  */
503 static int
504 parse_expr(struct search_node **headp, char *argv[])
505 {
506     struct search_node *sn, *newsn;
507     char or = 0, not = 0, type, **av;
508     debug_decl(parse_expr, SUDO_DEBUG_UTIL)
509
510     sn = *headp;
511     for (av = argv; *av; av++) {
512         switch (av[0][0]) {
513         case 'a': /* and (ignore) */
514             if (strncmp(*av, "and", strlen(*av)) != 0)
515                 goto bad;
516             continue;
517         case 'o': /* or */
518             if (strncmp(*av, "or", strlen(*av)) != 0)
519                 goto bad;
520             or = 1;
521             continue;
522         case '!': /* negate */
523             if (av[0][1] != '\0')
524                 goto bad;
525             not = 1;
526             continue;
527         case 'c': /* command */
528             if (av[0][1] == '\0')
529                 errorx(1, _("ambiguous expression \"%s\""), *av);
530             if (strncmp(*av, "cwd", strlen(*av)) == 0)
531                 type = ST_CWD;
532             else if (strncmp(*av, "command", strlen(*av)) == 0)
533                 type = ST_PATTERN;
534             else
535                 goto bad;
536             break;
537         case 'f': /* from date */
538             if (strncmp(*av, "fromdate", strlen(*av)) != 0)
539                 goto bad;
540             type = ST_FROMDATE;
541             break;
542         case 'g': /* runas group */
543             if (strncmp(*av, "group", strlen(*av)) != 0)
544                 goto bad;
545             type = ST_RUNASGROUP;
546             break;
547         case 'r': /* runas user */
548             if (strncmp(*av, "runas", strlen(*av)) != 0)
549                 goto bad;
550             type = ST_RUNASUSER;
551             break;
552         case 't': /* tty or to date */
553             if (av[0][1] == '\0')
554                 errorx(1, _("ambiguous expression \"%s\""), *av);
555             if (strncmp(*av, "todate", strlen(*av)) == 0)
556                 type = ST_TODATE;
557             else if (strncmp(*av, "tty", strlen(*av)) == 0)
558                 type = ST_TTY;
559             else
560                 goto bad;
561             break;
562         case 'u': /* user */
563             if (strncmp(*av, "user", strlen(*av)) != 0)
564                 goto bad;
565             type = ST_USER;
566             break;
567         case '(': /* start sub-expression */
568             if (av[0][1] != '\0')
569                 goto bad;
570             if (stack_top + 1 == STACK_NODE_SIZE) {
571                 errorx(1, _("too many parenthesized expressions, max %d"),
572                     STACK_NODE_SIZE);
573             }
574             node_stack[stack_top++] = sn;
575             type = ST_EXPR;
576             break;
577         case ')': /* end sub-expression */
578             if (av[0][1] != '\0')
579                 goto bad;
580             /* pop */
581             if (--stack_top < 0)
582                 errorx(1, _("unmatched ')' in expression"));
583             if (node_stack[stack_top])
584                 sn->next = node_stack[stack_top]->next;
585             debug_return_int(av - argv + 1);
586         bad:
587         default:
588             errorx(1, _("unknown search term \"%s\""), *av);
589             /* NOTREACHED */
590         }
591
592         /* Allocate new search node */
593         newsn = emalloc(sizeof(*newsn));
594         newsn->next = NULL;
595         newsn->type = type;
596         newsn->or = or;
597         newsn->negated = not;
598         if (type == ST_EXPR) {
599             av += parse_expr(&newsn->u.expr, av + 1);
600         } else {
601             if (*(++av) == NULL)
602                 errorx(1, _("%s requires an argument"), av[-1]);
603 #ifdef HAVE_REGCOMP
604             if (type == ST_PATTERN) {
605                 if (regcomp(&newsn->u.cmdre, *av, REG_EXTENDED|REG_NOSUB) != 0)
606                     errorx(1, _("invalid regular expression: %s"), *av);
607             } else
608 #endif
609             if (type == ST_TODATE || type == ST_FROMDATE) {
610                 newsn->u.tstamp = get_date(*av);
611                 if (newsn->u.tstamp == -1)
612                     errorx(1, _("could not parse date \"%s\""), *av);
613             } else {
614                 newsn->u.ptr = *av;
615             }
616         }
617         not = or = 0; /* reset state */
618         if (sn)
619             sn->next = newsn;
620         else
621             *headp = newsn;
622         sn = newsn;
623     }
624     if (stack_top)
625         errorx(1, _("unmatched '(' in expression"));
626     if (or)
627         errorx(1, _("illegal trailing \"or\""));
628     if (not)
629         errorx(1, _("illegal trailing \"!\""));
630
631     debug_return_int(av - argv);
632 }
633
634 static bool
635 match_expr(struct search_node *head, struct log_info *log)
636 {
637     struct search_node *sn;
638     bool matched = true, rc;
639     debug_decl(match_expr, SUDO_DEBUG_UTIL)
640
641     for (sn = head; sn; sn = sn->next) {
642         /* If we have no match, skip ahead to the next OR entry. */
643         if (!matched && !sn->or)
644             continue;
645
646         switch (sn->type) {
647         case ST_EXPR:
648             matched = match_expr(sn->u.expr, log);
649             break;
650         case ST_CWD:
651             matched = strcmp(sn->u.cwd, log->cwd) == 0;
652             break;
653         case ST_TTY:
654             matched = strcmp(sn->u.tty, log->tty) == 0;
655             break;
656         case ST_RUNASGROUP:
657             matched = strcmp(sn->u.runas_group, log->runas_group) == 0;
658             break;
659         case ST_RUNASUSER:
660             matched = strcmp(sn->u.runas_user, log->runas_user) == 0;
661             break;
662         case ST_USER:
663             matched = strcmp(sn->u.user, log->user) == 0;
664             break;
665         case ST_PATTERN:
666 #ifdef HAVE_REGCOMP
667             rc = regexec(&sn->u.cmdre, log->cmd, 0, NULL, 0);
668             if (rc && rc != REG_NOMATCH) {
669                 char buf[BUFSIZ];
670                 regerror(rc, &sn->u.cmdre, buf, sizeof(buf));
671                 errorx(1, "%s", buf);
672             }
673             matched = rc == REG_NOMATCH ? 0 : 1;
674 #else
675             matched = strstr(log.cmd, sn->u.pattern) != NULL;
676 #endif
677             break;
678         case ST_FROMDATE:
679             matched = log->tstamp >= sn->u.tstamp;
680             break;
681         case ST_TODATE:
682             matched = log->tstamp <= sn->u.tstamp;
683             break;
684         }
685         if (sn->negated)
686             matched = !matched;
687     }
688     debug_return_bool(matched);
689 }
690
691 static int
692 list_session(char *logfile, REGEX_T *re, const char *user, const char *tty)
693 {
694     FILE *fp;
695     char *buf = NULL, *cmd = NULL, *cwd = NULL, idbuf[7], *idstr, *cp;
696     struct log_info li;
697     size_t bufsize = 0, cwdsize = 0, cmdsize = 0;
698     int rval = -1;
699     debug_decl(list_session, SUDO_DEBUG_UTIL)
700
701     fp = fopen(logfile, "r");
702     if (fp == NULL) {
703         warning(_("unable to open %s"), logfile);
704         goto done;
705     }
706
707     /*
708      * ID file has three lines:
709      *  1) a log info line
710      *  2) cwd
711      *  3) command with args
712      */
713     if (getline(&buf, &bufsize, fp) == -1 ||
714         getline(&cwd, &cwdsize, fp) == -1 ||
715         getline(&cmd, &cmdsize, fp) == -1) {
716         goto done;
717     }
718
719     /* crack the log line: timestamp:user:runas_user:runas_group:tty */
720     buf[strcspn(buf, "\n")] = '\0';
721     if ((li.tstamp = atoi(buf)) == 0)
722         goto done;
723
724     if ((cp = strchr(buf, ':')) == NULL)
725         goto done;
726     *cp++ = '\0';
727     li.user = cp;
728
729     if ((cp = strchr(cp, ':')) == NULL)
730         goto done;
731     *cp++ = '\0';
732     li.runas_user = cp;
733
734     if ((cp = strchr(cp, ':')) == NULL)
735         goto done;
736     *cp++ = '\0';
737     li.runas_group = cp;
738
739     if ((cp = strchr(cp, ':')) == NULL)
740         goto done;
741     *cp++ = '\0';
742     li.tty = cp;
743
744     cwd[strcspn(cwd, "\n")] = '\0';
745     li.cwd = cwd;
746
747     cmd[strcspn(cmd, "\n")] = '\0';
748     li.cmd = cmd;
749
750     /* Match on search expression if there is one. */
751     if (search_expr && !match_expr(search_expr, &li))
752         goto done;
753
754     /* Convert from /var/log/sudo-sessions/00/00/01/log to 000001 */
755     cp = logfile + strlen(session_dir) + 1;
756     if (IS_IDLOG(cp)) {
757         idbuf[0] = cp[7];
758         idbuf[1] = cp[6];
759         idbuf[2] = cp[4];
760         idbuf[3] = cp[3];
761         idbuf[4] = cp[1];
762         idbuf[5] = cp[0];
763         idbuf[6] = '\0';
764         idstr = idbuf;
765     } else {
766         /* Not an id, just use the iolog_file portion. */
767         cp[strlen(cp) - 4] = '\0';
768         idstr = cp;
769     }
770     printf("%s : %s : TTY=%s ; CWD=%s ; USER=%s ; ",
771         get_timestr(li.tstamp, 1), li.user, li.tty, li.cwd, li.runas_user);
772     if (*li.runas_group)
773         printf("GROUP=%s ; ", li.runas_group);
774     printf("TSID=%s ; COMMAND=%s\n", idstr, li.cmd);
775
776     rval = 0;
777
778 done:
779     fclose(fp);
780     debug_return_int(rval);
781 }
782
783 /* XXX - always returns 0, calls error() on failure */
784 static int
785 find_sessions(const char *dir, REGEX_T *re, const char *user, const char *tty)
786 {
787     DIR *d;
788     struct dirent *dp;
789     struct stat sb;
790     size_t sdlen;
791     int len;
792     char pathbuf[PATH_MAX];
793     debug_decl(find_sessions, SUDO_DEBUG_UTIL)
794
795     d = opendir(dir);
796     if (d == NULL)
797         error(1, _("unable to open %s"), dir);
798
799     /* XXX - would be faster to chdir and use relative names */
800     sdlen = strlcpy(pathbuf, dir, sizeof(pathbuf));
801     if (sdlen + 1 >= sizeof(pathbuf)) {
802         errno = ENAMETOOLONG;
803         error(1, "%s/", dir);
804     }
805     pathbuf[sdlen++] = '/';
806     pathbuf[sdlen] = '\0';
807     while ((dp = readdir(d)) != NULL) {
808         /* Skip "." and ".." */
809         if (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' ||
810             (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
811             continue;
812
813         len = snprintf(&pathbuf[sdlen], sizeof(pathbuf) - sdlen,
814             "%s/log", dp->d_name);
815         if (len <= 0 || len >= sizeof(pathbuf) - sdlen) {
816             errno = ENAMETOOLONG;
817             error(1, "%s/%s/log", dir, dp->d_name);
818         }
819
820         /* Check for dir with a log file. */
821         if (lstat(pathbuf, &sb) == 0 && S_ISREG(sb.st_mode)) {
822             list_session(pathbuf, re, user, tty);
823         } else {
824             /* Strip off "/log" and recurse if a dir. */
825             pathbuf[sdlen + len - 4] = '\0';
826             if (lstat(pathbuf, &sb) == 0 && S_ISDIR(sb.st_mode))
827                 find_sessions(pathbuf, re, user, tty);
828         }
829     }
830     closedir(d);
831
832     debug_return_int(0);
833 }
834
835 /* XXX - always returns 0, calls error() on failure */
836 static int
837 list_sessions(int argc, char **argv, const char *pattern, const char *user,
838     const char *tty)
839 {
840     REGEX_T rebuf, *re = NULL;
841     debug_decl(list_sessions, SUDO_DEBUG_UTIL)
842
843     /* Parse search expression if present */
844     parse_expr(&search_expr, argv);
845
846 #ifdef HAVE_REGCOMP
847     /* optional regex */
848     if (pattern) {
849         re = &rebuf;
850         if (regcomp(re, pattern, REG_EXTENDED|REG_NOSUB) != 0)
851             errorx(1, _("invalid regex: %s"), pattern);
852     }
853 #else
854     re = (char *) pattern;
855 #endif /* HAVE_REGCOMP */
856
857     debug_return_int(find_sessions(session_dir, re, user, tty));
858 }
859
860 /*
861  * Check input for ' ', '<', '>'
862  * pause, slow, fast
863  */
864 static void
865 check_input(int ttyfd, double *speed)
866 {
867     fd_set *fdsr;
868     int nready, paused = 0;
869     struct timeval tv;
870     char ch;
871     ssize_t n;
872     debug_decl(check_input, SUDO_DEBUG_UTIL)
873
874     fdsr = (fd_set *)emalloc2(howmany(ttyfd + 1, NFDBITS), sizeof(fd_mask));
875
876     for (;;) {
877         FD_SET(ttyfd, fdsr);
878         tv.tv_sec = 0;
879         tv.tv_usec = 0;
880
881         nready = select(ttyfd + 1, fdsr, NULL, NULL, paused ? NULL : &tv);
882         if (nready != 1)
883             break;
884         n = read(ttyfd, &ch, 1);
885         if (n == 1) {
886             if (paused) {
887                 paused = 0;
888                 continue;
889             }
890             switch (ch) {
891             case ' ':
892                 paused = 1;
893                 break;
894             case '<':
895                 *speed /= 2;
896                 break;
897             case '>':
898                 *speed *= 2;
899                 break;
900             }
901         }
902     }
903     free(fdsr);
904     debug_return;
905 }
906
907 /*
908  * Parse a timing line, which is formatted as:
909  *      index sleep_time num_bytes
910  * Where index is IOFD_*, sleep_time is the number of seconds to sleep
911  * before writing the data and num_bytes is the number of bytes to output.
912  * Returns 1 on success and 0 on failure.
913  */
914 static int
915 parse_timing(buf, decimal, idx, seconds, nbytes)
916     const char *buf;
917     const char *decimal;
918     int *idx;
919     double *seconds;
920     size_t *nbytes;
921 {
922     unsigned long ul;
923     long l;
924     double d, fract = 0;
925     char *cp, *ep;
926     debug_decl(parse_timing, SUDO_DEBUG_UTIL)
927
928     /* Parse index */
929     ul = strtoul(buf, &ep, 10);
930     if (ul > IOFD_MAX)
931         goto bad;
932     *idx = (int)ul;
933     for (cp = ep + 1; isspace((unsigned char) *cp); cp++)
934         continue;
935
936     /*
937      * Parse number of seconds.  Sudo logs timing data in the C locale
938      * but this may not match the current locale so we cannot use strtod().
939      * Furthermore, sudo < 1.7.4 logged with the user's locale so we need
940      * to be able to parse those logs too.
941      */
942     errno = 0;
943     l = strtol(cp, &ep, 10);
944     if ((errno == ERANGE && (l == LONG_MAX || l == LONG_MIN)) ||
945         l < 0 || l > INT_MAX ||
946         (*ep != '.' && strncmp(ep, decimal, strlen(decimal)) != 0)) {
947         goto bad;
948     }
949     *seconds = (double)l;
950     cp = ep + (*ep == '.' ? 1 : strlen(decimal));
951     d = 10.0;
952     while (isdigit((unsigned char) *cp)) {
953         fract += (*cp - '0') / d;
954         d *= 10;
955         cp++;
956     }
957     *seconds += fract;
958     while (isspace((unsigned char) *cp))
959         cp++;
960
961     errno = 0;
962     ul = strtoul(cp, &ep, 10);
963     if (errno == ERANGE && ul == ULONG_MAX)
964         goto bad;
965     *nbytes = (size_t)ul;
966
967     debug_return_int(1);
968 bad:
969     debug_return_int(0);
970 }
971
972 static void
973 usage(int fatal)
974 {
975     fprintf(fatal ? stderr : stdout,
976         _("usage: %s [-h] [-d directory] [-m max_wait] [-s speed_factor] ID\n"),
977         getprogname());
978     fprintf(fatal ? stderr : stdout,
979         _("usage: %s [-h] [-d directory] -l [search expression]\n"),
980         getprogname());
981     if (fatal)
982         exit(1);
983 }
984
985 static void
986 help(void)
987 {
988     (void) printf(_("%s - replay sudo session logs\n\n"), getprogname());
989     usage(0);
990     (void) puts(_("\nOptions:\n"
991         "  -d directory     specify directory for session logs\n"
992         "  -f filter        specify which I/O type to display\n"
993         "  -h               display help message and exit\n"
994         "  -l [expression]  list available session IDs that match expression\n"
995         "  -m max_wait      max number of seconds to wait between events\n"
996         "  -s speed_factor  speed up or slow down output\n"
997         "  -V               display version information and exit"));
998     exit(0);
999 }
1000
1001 /*
1002  * Cleanup hook for error()/errorx()
1003   */
1004 void
1005 cleanup(int signo)
1006 {
1007     term_restore(STDIN_FILENO, 0);
1008     if (signo)
1009         kill(getpid(), signo);
1010 }