2 * Copyright (c) 2009-2011 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 "compat/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) |
125 * Info present in the I/O log file
138 * Handle expressions like:
139 * ( user millert or user root ) and tty console and command /bin/sh
142 struct search_node *next;
147 #define ST_RUNASUSER 5
148 #define ST_RUNASGROUP 6
149 #define ST_FROMDATE 7
167 struct search_node *expr;
172 #define STACK_NODE_SIZE 32
173 static struct search_node *node_stack[32];
174 static int stack_top;
176 static const char *session_dir = _PATH_SUDO_IO_LOGDIR;
178 static union io_fd io_fds[IOFD_MAX];
179 static const char *io_fnames[IOFD_MAX] = {
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);
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);
205 # define REGEX_T regex_t
207 # define REGEX_T char
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')
215 #define IS_IDLOG(s) ( \
216 isalnum((unsigned char)(s)[0]) && isalnum((unsigned char)(s)[1]) && \
218 isalnum((unsigned char)(s)[3]) && isalnum((unsigned char)(s)[4]) && \
220 isalnum((unsigned char)(s)[6]) && isalnum((unsigned char)(s)[7]) && \
221 (s)[8] == '/' && (s)[9] == 'l' && (s)[10] == 'o' && (s)[11] == 'g' && \
225 main(int argc, char *argv[])
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;
234 size_t len, nbytes, nread, off;
237 #if !defined(HAVE_GETPROGNAME) && !defined(HAVE___PROGNAME)
238 setprogname(argc > 0 ? argv[0] : "sudoreplay");
241 #ifdef HAVE_SETLOCALE
242 setlocale(LC_ALL, "");
243 decimal = localeconv()->decimal_point;
246 while ((ch = getopt(argc, argv, "d:f:hlm:s:V")) != -1) {
249 session_dir = optarg;
252 /* Set the replay filter. */
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);
262 errorx(1, "invalid filter option: %s", optarg);
273 max_wait = strtod(optarg, &ep);
274 if (*ep != '\0' || errno != 0)
275 errorx(1, "invalid max wait: %s", optarg);
279 speed = strtod(optarg, &ep);
280 if (*ep != '\0' || errno != 0)
281 errorx(1, "invalid speed factor: %s", optarg);
284 (void) printf("%s version %s\n", getprogname(), PACKAGE_VERSION);
296 exit(list_sessions(argc, argv, pattern, user, tty));
301 /* 6 digit ID in base 36, e.g. 01G712AB or free-form name */
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));
310 plen = snprintf(path, sizeof(path), "%s/%s/timing",
312 if (plen <= 0 || plen >= sizeof(path))
313 errorx(1, "%s/%s/timing: %s", session_dir,
314 id, strerror(ENAMETOOLONG));
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);
329 strlcat(path, "/log", sizeof(path));
330 lfile = fopen(path, "r");
332 error(1, "unable to open %s", path);
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);
341 printf("Replaying sudo session: %s", cp);
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);
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);
363 ch = fcntl(STDIN_FILENO, F_GETFL, 0);
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");
369 fdsw = (fd_set *)emalloc2(howmany(STDOUT_FILENO + 1, NFDBITS),
373 * Timing file consists of line of the format: "%f %d\n"
376 while (gzgets(io_fds[IOFD_TIMING].g, buf, sizeof(buf)) != NULL) {
378 while (fgets(buf, sizeof(buf), io_fds[IOFD_TIMING].f) != NULL) {
380 if (!parse_timing(buf, decimal, &idx, &seconds, &nbytes))
381 errorx(1, "invalid timing file line: %s", buf);
384 check_input(STDIN_FILENO, &speed);
386 /* Adjust delay using speed factor and clamp to max_wait */
387 to_wait = seconds / speed;
388 if (max_wait && to_wait > max_wait)
392 /* Even if we are not relaying, we still have to delay. */
393 if (io_fds[idx].v == NULL)
396 /* All output is sent to stdout. */
397 while (nbytes != 0) {
398 if (nbytes > sizeof(buf))
403 nread = gzread(io_fds[idx].g, buf, len);
405 nread = fread(buf, 1, len, io_fds[idx].f);
410 /* no stdio, must be unbuffered */
411 nwritten = write(STDOUT_FILENO, buf + off, nread - off);
412 if (nwritten == -1) {
415 if (errno == EAGAIN) {
416 FD_SET(STDOUT_FILENO, fdsw);
418 nready = select(STDOUT_FILENO + 1, NULL, fdsw, NULL, NULL);
419 } while (nready == -1 && errno == EINTR);
423 error(1, "writing to standard output");
426 } while (nread > off);
429 term_restore(STDIN_FILENO, 1);
436 struct timespec ts, rts;
440 * Typical max resolution is 1/HZ but we can't portably check that.
441 * If the interval is small enough, just ignore it.
447 rts.tv_nsec = (secs - (double) rts.tv_sec) * 1000000000.0;
449 memcpy(&ts, &rts, sizeof(ts));
450 rval = nanosleep(&ts, &rts);
451 } while (rval == -1 && errno == EINTR);
453 error(1, "nanosleep: tv_sec %ld, tv_nsec %ld", ts.tv_sec, ts.tv_nsec);
457 open_io_fd(char *path, int len, const char *suffix)
460 strlcat(path, suffix, PATH_MAX);
463 return gzopen(path, "r");
465 return fopen(path, "r");
470 * Build expression list from search args
473 parse_expr(struct search_node **headp, char *argv[])
475 struct search_node *sn, *newsn;
476 char or = 0, not = 0, type, **av;
479 for (av = argv; *av; av++) {
481 case 'a': /* and (ignore) */
482 if (strncmp(*av, "and", strlen(*av)) != 0)
486 if (strncmp(*av, "or", strlen(*av)) != 0)
490 case '!': /* negate */
491 if (av[0][1] != '\0')
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)
500 else if (strncmp(*av, "command", strlen(*av)) == 0)
505 case 'f': /* from date */
506 if (strncmp(*av, "fromdate", strlen(*av)) != 0)
510 case 'g': /* runas group */
511 if (strncmp(*av, "group", strlen(*av)) != 0)
513 type = ST_RUNASGROUP;
515 case 'r': /* runas user */
516 if (strncmp(*av, "runas", strlen(*av)) != 0)
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)
525 else if (strncmp(*av, "tty", strlen(*av)) == 0)
531 if (strncmp(*av, "user", strlen(*av)) != 0)
535 case '(': /* start sub-expression */
536 if (av[0][1] != '\0')
538 if (stack_top + 1 == STACK_NODE_SIZE) {
539 errorx(1, "too many parenthesized expressions, max %d",
542 node_stack[stack_top++] = sn;
545 case ')': /* end sub-expression */
546 if (av[0][1] != '\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;
556 errorx(1, "unknown search term \"%s\"", *av);
560 /* Allocate new search node */
561 newsn = emalloc(sizeof(*newsn));
565 newsn->negated = not;
566 if (type == ST_EXPR) {
567 av += parse_expr(&newsn->u.expr, av + 1);
570 errorx(1, "%s requires an argument", av[-1]);
572 if (type == ST_PATTERN) {
573 if (regcomp(&newsn->u.cmdre, *av, REG_EXTENDED|REG_NOSUB) != 0)
574 errorx(1, "invalid regex: %s", *av);
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);
585 not = or = 0; /* reset state */
593 errorx(1, "unmatched '(' in expression");
595 errorx(1, "illegal trailing \"or\"");
597 errorx(1, "illegal trailing \"!\"");
603 match_expr(struct search_node *head, struct log_info *log)
605 struct search_node *sn;
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)
615 matched = match_expr(sn->u.expr, log);
618 matched = strcmp(sn->u.cwd, log->cwd) == 0;
621 matched = strcmp(sn->u.tty, log->tty) == 0;
624 matched = strcmp(sn->u.runas_group, log->runas_group) == 0;
627 matched = strcmp(sn->u.runas_user, log->runas_user) == 0;
630 matched = strcmp(sn->u.user, log->user) == 0;
634 rc = regexec(&sn->u.cmdre, log->cmd, 0, NULL, 0);
635 if (rc && rc != REG_NOMATCH) {
637 regerror(rc, &sn->u.cmdre, buf, sizeof(buf));
638 errorx(1, "%s", buf);
640 matched = rc == REG_NOMATCH ? 0 : 1;
642 matched = strstr(log.cmd, sn->u.pattern) != NULL;
646 matched = log->tstamp >= sn->u.tstamp;
649 matched = log->tstamp <= sn->u.tstamp;
659 list_session(char *logfile, REGEX_T *re, const char *user, const char *tty)
662 char *buf = NULL, *cmd = NULL, *cwd = NULL, idbuf[7], *idstr, *cp;
664 size_t bufsize = 0, cwdsize = 0, cmdsize = 0;
667 fp = fopen(logfile, "r");
669 warning("unable to open %s", logfile);
674 * ID file has three lines:
677 * 3) command with args
679 if (getline(&buf, &bufsize, fp) == -1 ||
680 getline(&cwd, &cwdsize, fp) == -1 ||
681 getline(&cmd, &cmdsize, fp) == -1) {
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)
690 if ((cp = strchr(buf, ':')) == NULL)
695 if ((cp = strchr(cp, ':')) == NULL)
700 if ((cp = strchr(cp, ':')) == NULL)
705 if ((cp = strchr(cp, ':')) == NULL)
710 cwd[strcspn(cwd, "\n")] = '\0';
713 cmd[strcspn(cmd, "\n")] = '\0';
716 /* Match on search expression if there is one. */
717 if (search_expr && !match_expr(search_expr, &li))
720 /* Convert from /var/log/sudo-sessions/00/00/01/log to 000001 */
721 cp = logfile + strlen(session_dir) + 1;
732 /* Not an id, just use the iolog_file portion. */
733 cp[strlen(cp) - 4] = '\0';
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);
739 printf("GROUP=%s ; ", li.runas_group);
740 printf("TSID=%s ; COMMAND=%s\n", idstr, li.cmd);
750 find_sessions(const char *dir, REGEX_T *re, const char *user, const char *tty)
757 char pathbuf[PATH_MAX];
761 error(1, "unable to open %s", dir);
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);
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')))
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);
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);
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);
800 list_sessions(int argc, char **argv, const char *pattern, const char *user,
803 REGEX_T rebuf, *re = NULL;
805 /* Parse search expression if present */
806 parse_expr(&search_expr, argv);
812 if (regcomp(re, pattern, REG_EXTENDED|REG_NOSUB) != 0)
813 errorx(1, "invalid regex: %s", pattern);
816 re = (char *) pattern;
817 #endif /* HAVE_REGCOMP */
819 return find_sessions(session_dir, re, user, tty);
823 * Check input for ' ', '<', '>'
827 check_input(int ttyfd, double *speed)
830 int nready, paused = 0;
835 fdsr = (fd_set *)emalloc2(howmany(ttyfd + 1, NFDBITS), sizeof(fd_mask));
842 nready = select(ttyfd + 1, fdsr, NULL, NULL, paused ? NULL : &tv);
845 n = read(ttyfd, &ch, 1);
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.
875 parse_timing(buf, decimal, idx, seconds, nbytes)
888 ul = strtoul(buf, &ep, 10);
892 for (cp = ep + 1; isspace((unsigned char) *cp); cp++)
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.
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)) {
908 *seconds = (double)l;
909 cp = ep + (*ep == '.' ? 1 : strlen(decimal));
911 while (isdigit((unsigned char) *cp)) {
912 fract += (*cp - '0') / d;
917 while (isspace((unsigned char) *cp))
921 ul = strtoul(cp, &ep, 10);
922 if (errno == ERANGE && ul == ULONG_MAX)
924 *nbytes = (size_t)ul;
934 fprintf(fatal ? stderr : stdout,
935 "usage: %s [-h] [-d directory] [-m max_wait] [-s speed_factor] ID\n",
937 fprintf(fatal ? stderr : stdout,
938 "usage: %s [-h] [-d directory] -l [search expression]\n",
947 (void) printf("%s - replay sudo session logs\n\n", getprogname());
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");
961 * Cleanup hook for error()/errorx()
966 term_restore(STDIN_FILENO, 0);
968 kill(getpid(), signo);