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