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