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