2 * Copyright (c) 2009-2010 Todd C. Miller <Todd.Miller@courtesan.com>
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.
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.
19 #include <sys/types.h>
20 #include <sys/param.h>
21 #ifdef HAVE_SYS_SYSMACROS_H
22 # include <sys/sysmacros.h>
27 #include <sys/ioctl.h>
28 #ifdef HAVE_SYS_SELECT_H
29 #include <sys/select.h>
30 #endif /* HAVE_SYS_SELECT_H */
39 #endif /* STDC_HEADERS */
41 # if defined(HAVE_MEMORY_H) && !defined(STDC_HEADERS)
45 #endif /* HAVE_STRING_H */
48 #endif /* HAVE_STRINGS_H */
51 #endif /* HAVE_UNISTD_H */
52 #if TIME_WITH_SYS_TIME
56 # include "emul/timespec.h"
64 # define NAMLEN(dirent) strlen((dirent)->d_name)
66 # define dirent direct
67 # define NAMLEN(dirent) (dirent)->d_namlen
68 # ifdef HAVE_SYS_NDIR_H
69 # include <sys/ndir.h>
71 # ifdef HAVE_SYS_DIR_H
89 #include <pathnames.h>
96 # define LINE_MAX 2048
99 /* Must match the defines in iolog.c */
101 #define IOFD_STDOUT 1
102 #define IOFD_STDERR 2
104 #define IOFD_TTYOUT 4
105 #define IOFD_TIMING 5
108 /* Bitmap of iofds to be replayed */
109 unsigned int replay_filter = (1 << IOFD_STDOUT) | (1 << IOFD_STDERR) |
128 * Info present in the I/O log file
141 * Handle expressions like:
142 * ( user millert or user root ) and tty console and command /bin/sh
145 struct search_node *next;
150 #define ST_RUNASUSER 5
151 #define ST_RUNASGROUP 6
152 #define ST_FROMDATE 7
170 struct search_node *expr;
175 #define STACK_NODE_SIZE 32
176 static struct search_node *node_stack[32];
177 static int stack_top;
179 static const char *session_dir = _PATH_SUDO_IO_LOGDIR;
181 static union io_fd io_fds[IOFD_MAX];
182 static const char *io_fnames[IOFD_MAX] = {
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));
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));
208 # define REGEX_T regex_t
210 # define REGEX_T char
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')
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;
230 size_t len, nbytes, nread, off;
236 #ifdef HAVE_SETLOCALE
237 setlocale(LC_ALL, "");
238 decimal = localeconv()->decimal_point;
241 while ((ch = getopt(argc, argv, "d:f:hlm:s:V")) != -1) {
244 session_dir = optarg;
247 /* Set the replay filter. */
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);
257 errorx(1, "invalid filter option: %s", optarg);
268 max_wait = strtod(optarg, &ep);
269 if (*ep != '\0' || errno != 0)
270 errorx(1, "invalid max wait: %s", optarg);
274 speed = strtod(optarg, &ep);
275 if (*ep != '\0' || errno != 0)
276 errorx(1, "invalid speed factor: %s", optarg);
279 (void) printf("%s version %s\n", getprogname(), PACKAGE_VERSION);
291 exit(list_sessions(argc, argv, pattern, user, tty));
296 /* 6 digit ID in base 36, e.g. 01G712AB */
299 errorx(1, "invalid ID %s", id);
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));
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);
319 strlcat(path, "/log", sizeof(path));
320 lfile = fopen(path, "r");
322 error(1, "unable to open %s", path);
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);
331 printf("Replaying sudo session: %s", cp);
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);
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);
353 ch = fcntl(STDIN_FILENO, F_GETFL, 0);
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");
359 fdsw = (fd_set *)emalloc2(howmany(STDOUT_FILENO + 1, NFDBITS),
363 * Timing file consists of line of the format: "%f %d\n"
366 while (gzgets(io_fds[IOFD_TIMING].g, buf, sizeof(buf)) != NULL) {
368 while (fgets(buf, sizeof(buf), io_fds[IOFD_TIMING].f) != NULL) {
370 if (!parse_timing(buf, decimal, &idx, &seconds, &nbytes))
371 errorx(1, "invalid timing file line: %s", buf);
374 check_input(STDIN_FILENO, &speed);
376 /* Adjust delay using speed factor and clamp to max_wait */
377 to_wait = seconds / speed;
378 if (max_wait && to_wait > max_wait)
382 /* Even if we are not relaying, we still have to delay. */
383 if (io_fds[idx].v == NULL)
386 /* All output is sent to stdout. */
387 while (nbytes != 0) {
388 if (nbytes > sizeof(buf))
393 nread = gzread(io_fds[idx].g, buf, len);
395 nread = fread(buf, 1, len, io_fds[idx].f);
400 /* no stdio, must be unbuffered */
401 nwritten = write(STDOUT_FILENO, buf + off, nread - off);
402 if (nwritten == -1) {
405 if (errno == EAGAIN) {
406 FD_SET(STDOUT_FILENO, fdsw);
408 nready = select(STDOUT_FILENO + 1, NULL, fdsw, NULL, NULL);
409 } while (nready == -1 && errno == EINTR);
413 error(1, "writing to standard output");
416 } while (nread > off);
419 term_restore(STDIN_FILENO, 1);
427 struct timespec ts, rts;
431 * Typical max resolution is 1/HZ but we can't portably check that.
432 * If the interval is small enough, just ignore it.
438 rts.tv_nsec = (secs - (double) rts.tv_sec) * 1000000000.0;
440 memcpy(&ts, &rts, sizeof(ts));
441 rval = nanosleep(&ts, &rts);
442 } while (rval == -1 && errno == EINTR);
444 error(1, "nanosleep: tv_sec %ld, tv_nsec %ld", ts.tv_sec, ts.tv_nsec);
448 open_io_fd(path, len, suffix)
454 strlcat(path, suffix, PATH_MAX);
457 return gzopen(path, "r");
459 return fopen(path, "r");
464 * Build expression list from search args
467 parse_expr(headp, argv)
468 struct search_node **headp;
471 struct search_node *sn, *newsn;
472 char or = 0, not = 0, type, **av;
475 for (av = argv; *av; av++) {
477 case 'a': /* and (ignore) */
478 if (strncmp(*av, "and", strlen(*av)) != 0)
482 if (strncmp(*av, "or", strlen(*av)) != 0)
486 case '!': /* negate */
487 if (av[0][1] != '\0')
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)
496 else if (strncmp(*av, "command", strlen(*av)) == 0)
501 case 'f': /* from date */
502 if (strncmp(*av, "fromdate", strlen(*av)) != 0)
506 case 'g': /* runas group */
507 if (strncmp(*av, "group", strlen(*av)) != 0)
509 type = ST_RUNASGROUP;
511 case 'r': /* runas user */
512 if (strncmp(*av, "runas", strlen(*av)) != 0)
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)
521 else if (strncmp(*av, "tty", strlen(*av)) == 0)
527 if (strncmp(*av, "user", strlen(*av)) != 0)
531 case '(': /* start sub-expression */
532 if (av[0][1] != '\0')
534 if (stack_top + 1 == STACK_NODE_SIZE) {
535 errorx(1, "too many parenthesized expressions, max %d",
538 node_stack[stack_top++] = sn;
541 case ')': /* end sub-expression */
542 if (av[0][1] != '\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;
552 errorx(1, "unknown search term \"%s\"", *av);
556 /* Allocate new search node */
557 newsn = emalloc(sizeof(*newsn));
561 newsn->negated = not;
562 if (type == ST_EXPR) {
563 av += parse_expr(&newsn->u.expr, av + 1);
566 errorx(1, "%s requires an argument", av[-1]);
568 if (type == ST_PATTERN) {
569 if (regcomp(&newsn->u.cmdre, *av, REG_EXTENDED|REG_NOSUB) != 0)
570 errorx(1, "invalid regex: %s", *av);
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);
581 not = or = 0; /* reset state */
589 errorx(1, "unmatched '(' in expression");
591 errorx(1, "illegal trailing \"or\"");
593 errorx(1, "illegal trailing \"!\"");
599 match_expr(head, log)
600 struct search_node *head;
601 struct log_info *log;
603 struct search_node *sn;
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)
613 matched = match_expr(sn->u.expr, log);
616 matched = strcmp(sn->u.cwd, log->cwd) == 0;
619 matched = strcmp(sn->u.tty, log->tty) == 0;
622 matched = strcmp(sn->u.runas_group, log->runas_group) == 0;
625 matched = strcmp(sn->u.runas_user, log->runas_user) == 0;
628 matched = strcmp(sn->u.user, log->user) == 0;
632 rc = regexec(&sn->u.cmdre, log->cmd, 0, NULL, 0);
633 if (rc && rc != REG_NOMATCH) {
635 regerror(rc, &sn->u.cmdre, buf, sizeof(buf));
636 errorx(1, "%s", buf);
638 matched = rc == REG_NOMATCH ? 0 : 1;
640 matched = strstr(log.cmd, sn->u.pattern) != NULL;
644 matched = log->tstamp >= sn->u.tstamp;
647 matched = log->tstamp <= sn->u.tstamp;
657 list_session_dir(pathbuf, re, user, tty)
666 char *buf = NULL, *cmd = NULL, *cwd = NULL, idstr[7], *cp;
668 size_t bufsize = 0, cwdsize = 0, cmdsize = 0, plen;
670 plen = strlen(pathbuf);
671 d = opendir(pathbuf);
672 if (d == NULL && errno != ENOTDIR) {
673 warning("cannot opendir %s", pathbuf);
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]))
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");
692 warning("unable to open %s", pathbuf);
697 * ID file has three lines:
700 * 3) command with args
702 if (getline(&buf, &bufsize, fp) == -1 ||
703 getline(&cwd, &cwdsize, fp) == -1 ||
704 getline(&cmd, &cmdsize, fp) == -1) {
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)
715 if ((cp = strchr(buf, ':')) == NULL)
720 if ((cp = strchr(cp, ':')) == NULL)
725 if ((cp = strchr(cp, ':')) == NULL)
730 if ((cp = strchr(cp, ':')) == NULL)
735 cwd[strcspn(cwd, "\n")] = '\0';
738 cmd[strcspn(cmd, "\n")] = '\0';
741 /* Match on search expression if there is one. */
742 if (search_expr && !match_expr(search_expr, &li))
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];
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);
756 printf("GROUP=%s ; ", li.runas_group);
757 printf("TSID=%s ; COMMAND=%s\n", idstr, li.cmd);
763 list_sessions(argc, argv, pattern, user, tty)
771 struct dirent *dp1, *dp2;
772 REGEX_T rebuf, *re = NULL;
774 char pathbuf[PATH_MAX];
776 /* Parse search expression if present */
777 parse_expr(&search_expr, argv);
779 d1 = opendir(session_dir);
781 error(1, "unable to open %s", session_dir);
787 if (regcomp(re, pattern, REG_EXTENDED|REG_NOSUB) != 0)
788 errorx(1, "invalid regex: %s", pattern);
791 re = (char *) pattern;
792 #endif /* HAVE_REGCOMP */
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);
801 * Three levels of directory, e.g. 00/00/00 .. ZZ/ZZ/ZZ
802 * We do a depth-first traversal.
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]))
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);
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]))
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);
835 * Check input for ' ', '<', '>'
839 check_input(ttyfd, speed)
844 int nready, paused = 0;
849 fdsr = (fd_set *)emalloc2(howmany(ttyfd + 1, NFDBITS), sizeof(fd_mask));
856 nready = select(ttyfd + 1, fdsr, NULL, NULL, paused ? NULL : &tv);
859 n = read(ttyfd, &ch, 1);
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.
889 parse_timing(buf, decimal, idx, seconds, nbytes)
902 ul = strtoul(buf, &ep, 10);
906 for (cp = ep + 1; isspace((unsigned char) *cp); cp++)
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.
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)) {
922 *seconds = (double)l;
923 cp = ep + (*ep == '.' ? 1 : strlen(decimal));
925 while (isdigit((unsigned char) *cp)) {
926 fract += (*cp - '0') / d;
931 while (isspace((unsigned char) *cp))
935 ul = strtoul(cp, &ep, 10);
936 if (errno == ERANGE && ul == ULONG_MAX)
938 *nbytes = (size_t)ul;
949 fprintf(fatal ? stderr : stdout,
950 "usage: %s [-h] [-d directory] [-f filter] [-m max_wait] [-s speed_factor] ID\n",
952 fprintf(fatal ? stderr : stdout,
953 "usage: %s [-h] [-d directory] -l [search expression]\n",
962 (void) printf("%s - replay sudo session logs\n\n", getprogname());
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");
976 * Cleanup hook for error()/errorx()
982 term_restore(STDIN_FILENO, 0);
984 kill(getpid(), signo);