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>
97 # define LINE_MAX 2048
100 /* Must match the defines in iolog.c */
102 #define IOFD_STDOUT 1
103 #define IOFD_STDERR 2
105 #define IOFD_TTYOUT 4
106 #define IOFD_TIMING 5
109 /* Bitmap of iofds to be replayed */
110 unsigned int replay_filter = (1 << IOFD_STDOUT) | (1 << IOFD_STDERR) |
126 * Info present in the I/O log file
139 * Handle expressions like:
140 * ( user millert or user root ) and tty console and command /bin/sh
143 struct search_node *next;
148 #define ST_RUNASUSER 5
149 #define ST_RUNASGROUP 6
150 #define ST_FROMDATE 7
168 struct search_node *expr;
173 #define STACK_NODE_SIZE 32
174 static struct search_node *node_stack[32];
175 static int stack_top;
177 static const char *session_dir = _PATH_SUDO_IO_LOGDIR;
179 static union io_fd io_fds[IOFD_MAX];
180 static const char *io_fnames[IOFD_MAX] = {
189 extern time_t get_date(char *);
190 extern char *get_timestr(time_t, int);
191 extern int term_raw(int, int);
192 extern int term_restore(int, int);
193 extern void zero_bytes(volatile void *, size_t);
196 static int list_sessions(int, char **, const char *, const char *, const char *);
197 static int parse_expr(struct search_node **, char **);
198 static void check_input(int, double *);
199 static void delay(double);
200 static void help(void) __attribute__((__noreturn__));
201 static void usage(int);
202 static int open_io_fd(char *pathbuf, int len, const char *suffix, union io_fd *fdp);
203 static int parse_timing(const char *buf, const char *decimal, int *idx, double *seconds, size_t *nbytes);
206 # define REGEX_T regex_t
208 # define REGEX_T char
211 #define VALID_ID(s) (isalnum((unsigned char)(s)[0]) && \
212 isalnum((unsigned char)(s)[1]) && isalnum((unsigned char)(s)[2]) && \
213 isalnum((unsigned char)(s)[3]) && isalnum((unsigned char)(s)[4]) && \
214 isalnum((unsigned char)(s)[5]) && (s)[6] == '\0')
216 #define IS_IDLOG(s) ( \
217 isalnum((unsigned char)(s)[0]) && isalnum((unsigned char)(s)[1]) && \
219 isalnum((unsigned char)(s)[3]) && isalnum((unsigned char)(s)[4]) && \
221 isalnum((unsigned char)(s)[6]) && isalnum((unsigned char)(s)[7]) && \
222 (s)[8] == '/' && (s)[9] == 'l' && (s)[10] == 'o' && (s)[11] == 'g' && \
226 main(int argc, char *argv[])
228 int ch, idx, plen, nready, interactive = 0, listonly = 0;
229 const char *id, *user = NULL, *pattern = NULL, *tty = NULL, *decimal = ".";
230 char path[PATH_MAX], buf[LINE_MAX], *cp, *ep;
231 double seconds, to_wait, speed = 1.0, max_wait = 0;
235 size_t len, nbytes, nread, off;
238 #if !defined(HAVE_GETPROGNAME) && !defined(HAVE___PROGNAME)
239 setprogname(argc > 0 ? argv[0] : "sudoreplay");
242 #ifdef HAVE_SETLOCALE
243 setlocale(LC_ALL, "");
244 decimal = localeconv()->decimal_point;
246 bindtextdomain("sudoers", LOCALEDIR); /* XXX - should have sudoreplay domain */
247 textdomain("sudoers");
249 while ((ch = getopt(argc, argv, "d:f:hlm:s:V")) != -1) {
252 session_dir = optarg;
255 /* Set the replay filter. */
257 for (cp = strtok(optarg, ","); cp; cp = strtok(NULL, ",")) {
258 if (strcmp(cp, "stdout") == 0)
259 SET(replay_filter, 1 << IOFD_STDOUT);
260 else if (strcmp(cp, "stderr") == 0)
261 SET(replay_filter, 1 << IOFD_STDERR);
262 else if (strcmp(cp, "ttyout") == 0)
263 SET(replay_filter, 1 << IOFD_TTYOUT);
265 errorx(1, _("invalid filter option: %s"), optarg);
276 max_wait = strtod(optarg, &ep);
277 if (*ep != '\0' || errno != 0)
278 errorx(1, _("invalid max wait: %s"), optarg);
282 speed = strtod(optarg, &ep);
283 if (*ep != '\0' || errno != 0)
284 errorx(1, _("invalid speed factor: %s"), optarg);
287 (void) printf(_("%s version %s\n"), getprogname(), PACKAGE_VERSION);
299 exit(list_sessions(argc, argv, pattern, user, tty));
304 /* 6 digit ID in base 36, e.g. 01G712AB or free-form name */
307 plen = snprintf(path, sizeof(path), "%s/%.2s/%.2s/%.2s/timing",
308 session_dir, id, &id[2], &id[4]);
309 if (plen <= 0 || plen >= sizeof(path))
310 errorx(1, _("%s/%.2s/%.2s/%.2s/timing: %s"), session_dir,
311 id, &id[2], &id[4], strerror(ENAMETOOLONG));
313 plen = snprintf(path, sizeof(path), "%s/%s/timing",
315 if (plen <= 0 || plen >= sizeof(path))
316 errorx(1, _("%s/%s/timing: %s"), session_dir,
317 id, strerror(ENAMETOOLONG));
321 /* Open files for replay, applying replay filter for the -f flag. */
322 for (idx = 0; idx < IOFD_MAX; idx++) {
323 if (ISSET(replay_filter, 1 << idx) || idx == IOFD_TIMING) {
324 if (open_io_fd(path, plen, io_fnames[idx], &io_fds[idx]) == -1)
325 error(1, _("unable to open %s"), path);
331 strlcat(path, "/log", sizeof(path));
332 lfile = fopen(path, "r");
334 error(1, _("unable to open %s"), path);
337 /* Pull out command (third line). */
338 if (getline(&cp, &len, lfile) == -1 ||
339 getline(&cp, &len, lfile) == -1 ||
340 getline(&cp, &len, lfile) == -1) {
341 errorx(1, _("invalid log file %s"), path);
343 printf(_("Replaying sudo session: %s"), cp);
348 zero_bytes(&sa, sizeof(sa));
349 sigemptyset(&sa.sa_mask);
350 sa.sa_flags = SA_RESETHAND;
351 sa.sa_handler = cleanup;
352 (void) sigaction(SIGINT, &sa, NULL);
353 (void) sigaction(SIGKILL, &sa, NULL);
354 (void) sigaction(SIGTERM, &sa, NULL);
355 (void) sigaction(SIGHUP, &sa, NULL);
356 sa.sa_flags = SA_RESTART;
357 sa.sa_handler = SIG_IGN;
358 (void) sigaction(SIGTSTP, &sa, NULL);
359 (void) sigaction(SIGQUIT, &sa, NULL);
361 /* XXX - read user input from /dev/tty and set STDOUT to raw if not a pipe */
362 /* Set stdin to raw mode if it is a tty */
363 interactive = isatty(STDIN_FILENO);
365 ch = fcntl(STDIN_FILENO, F_GETFL, 0);
367 (void) fcntl(STDIN_FILENO, F_SETFL, ch | O_NONBLOCK);
368 if (!term_raw(STDIN_FILENO, 1))
369 error(1, _("unable to set tty to raw mode"));
371 fdsw = (fd_set *)emalloc2(howmany(STDOUT_FILENO + 1, NFDBITS),
375 * Timing file consists of line of the format: "%f %d\n"
378 while (gzgets(io_fds[IOFD_TIMING].g, buf, sizeof(buf)) != NULL) {
380 while (fgets(buf, sizeof(buf), io_fds[IOFD_TIMING].f) != NULL) {
382 if (!parse_timing(buf, decimal, &idx, &seconds, &nbytes))
383 errorx(1, _("invalid timing file line: %s"), buf);
386 check_input(STDIN_FILENO, &speed);
388 /* Adjust delay using speed factor and clamp to max_wait */
389 to_wait = seconds / speed;
390 if (max_wait && to_wait > max_wait)
394 /* Even if we are not relaying, we still have to delay. */
395 if (io_fds[idx].v == NULL)
398 /* All output is sent to stdout. */
399 while (nbytes != 0) {
400 if (nbytes > sizeof(buf))
405 nread = gzread(io_fds[idx].g, buf, len);
407 nread = fread(buf, 1, len, io_fds[idx].f);
412 /* no stdio, must be unbuffered */
413 nwritten = write(STDOUT_FILENO, buf + off, nread - off);
414 if (nwritten == -1) {
417 if (errno == EAGAIN) {
418 FD_SET(STDOUT_FILENO, fdsw);
420 nready = select(STDOUT_FILENO + 1, NULL, fdsw, NULL, NULL);
421 } while (nready == -1 && errno == EINTR);
425 error(1, _("writing to standard output"));
428 } while (nread > off);
431 term_restore(STDIN_FILENO, 1);
438 struct timespec ts, rts;
442 * Typical max resolution is 1/HZ but we can't portably check that.
443 * If the interval is small enough, just ignore it.
449 rts.tv_nsec = (secs - (double) rts.tv_sec) * 1000000000.0;
451 memcpy(&ts, &rts, sizeof(ts));
452 rval = nanosleep(&ts, &rts);
453 } while (rval == -1 && errno == EINTR);
455 error(1, _("nanosleep: tv_sec %ld, tv_nsec %ld"),
456 (long)ts.tv_sec, (long)ts.tv_nsec);
461 open_io_fd(char *path, int len, const char *suffix, union io_fd *fdp)
464 strlcat(path, suffix, PATH_MAX);
467 fdp->g = gzopen(path, "r");
468 return fdp->g ? 0 : -1;
470 fdp->f = fopen(path, "r");
471 return fdp->f ? 0 : -1;
476 * Build expression list from search args
479 parse_expr(struct search_node **headp, char *argv[])
481 struct search_node *sn, *newsn;
482 char or = 0, not = 0, type, **av;
485 for (av = argv; *av; av++) {
487 case 'a': /* and (ignore) */
488 if (strncmp(*av, "and", strlen(*av)) != 0)
492 if (strncmp(*av, "or", strlen(*av)) != 0)
496 case '!': /* negate */
497 if (av[0][1] != '\0')
501 case 'c': /* command */
502 if (av[0][1] == '\0')
503 errorx(1, _("ambiguous expression \"%s\""), *av);
504 if (strncmp(*av, "cwd", strlen(*av)) == 0)
506 else if (strncmp(*av, "command", strlen(*av)) == 0)
511 case 'f': /* from date */
512 if (strncmp(*av, "fromdate", strlen(*av)) != 0)
516 case 'g': /* runas group */
517 if (strncmp(*av, "group", strlen(*av)) != 0)
519 type = ST_RUNASGROUP;
521 case 'r': /* runas user */
522 if (strncmp(*av, "runas", strlen(*av)) != 0)
526 case 't': /* tty or to date */
527 if (av[0][1] == '\0')
528 errorx(1, _("ambiguous expression \"%s\""), *av);
529 if (strncmp(*av, "todate", strlen(*av)) == 0)
531 else if (strncmp(*av, "tty", strlen(*av)) == 0)
537 if (strncmp(*av, "user", strlen(*av)) != 0)
541 case '(': /* start sub-expression */
542 if (av[0][1] != '\0')
544 if (stack_top + 1 == STACK_NODE_SIZE) {
545 errorx(1, _("too many parenthesized expressions, max %d"),
548 node_stack[stack_top++] = sn;
551 case ')': /* end sub-expression */
552 if (av[0][1] != '\0')
556 errorx(1, _("unmatched ')' in expression"));
557 if (node_stack[stack_top])
558 sn->next = node_stack[stack_top]->next;
559 return av - argv + 1;
562 errorx(1, _("unknown search term \"%s\""), *av);
566 /* Allocate new search node */
567 newsn = emalloc(sizeof(*newsn));
571 newsn->negated = not;
572 if (type == ST_EXPR) {
573 av += parse_expr(&newsn->u.expr, av + 1);
576 errorx(1, _("%s requires an argument"), av[-1]);
578 if (type == ST_PATTERN) {
579 if (regcomp(&newsn->u.cmdre, *av, REG_EXTENDED|REG_NOSUB) != 0)
580 errorx(1, _("invalid regular expression: %s"), *av);
583 if (type == ST_TODATE || type == ST_FROMDATE) {
584 newsn->u.tstamp = get_date(*av);
585 if (newsn->u.tstamp == -1)
586 errorx(1, _("could not parse date \"%s\""), *av);
591 not = or = 0; /* reset state */
599 errorx(1, _("unmatched '(' in expression"));
601 errorx(1, _("illegal trailing \"or\""));
603 errorx(1, _("illegal trailing \"!\""));
609 match_expr(struct search_node *head, struct log_info *log)
611 struct search_node *sn;
614 for (sn = head; sn; sn = sn->next) {
615 /* If we have no match, skip ahead to the next OR entry. */
616 if (!matched && !sn->or)
621 matched = match_expr(sn->u.expr, log);
624 matched = strcmp(sn->u.cwd, log->cwd) == 0;
627 matched = strcmp(sn->u.tty, log->tty) == 0;
630 matched = strcmp(sn->u.runas_group, log->runas_group) == 0;
633 matched = strcmp(sn->u.runas_user, log->runas_user) == 0;
636 matched = strcmp(sn->u.user, log->user) == 0;
640 rc = regexec(&sn->u.cmdre, log->cmd, 0, NULL, 0);
641 if (rc && rc != REG_NOMATCH) {
643 regerror(rc, &sn->u.cmdre, buf, sizeof(buf));
644 errorx(1, "%s", buf);
646 matched = rc == REG_NOMATCH ? 0 : 1;
648 matched = strstr(log.cmd, sn->u.pattern) != NULL;
652 matched = log->tstamp >= sn->u.tstamp;
655 matched = log->tstamp <= sn->u.tstamp;
665 list_session(char *logfile, REGEX_T *re, const char *user, const char *tty)
668 char *buf = NULL, *cmd = NULL, *cwd = NULL, idbuf[7], *idstr, *cp;
670 size_t bufsize = 0, cwdsize = 0, cmdsize = 0;
673 fp = fopen(logfile, "r");
675 warning(_("unable to open %s"), logfile);
680 * ID file has three lines:
683 * 3) command with args
685 if (getline(&buf, &bufsize, fp) == -1 ||
686 getline(&cwd, &cwdsize, fp) == -1 ||
687 getline(&cmd, &cmdsize, fp) == -1) {
691 /* crack the log line: timestamp:user:runas_user:runas_group:tty */
692 buf[strcspn(buf, "\n")] = '\0';
693 if ((li.tstamp = atoi(buf)) == 0)
696 if ((cp = strchr(buf, ':')) == NULL)
701 if ((cp = strchr(cp, ':')) == NULL)
706 if ((cp = strchr(cp, ':')) == NULL)
711 if ((cp = strchr(cp, ':')) == NULL)
716 cwd[strcspn(cwd, "\n")] = '\0';
719 cmd[strcspn(cmd, "\n")] = '\0';
722 /* Match on search expression if there is one. */
723 if (search_expr && !match_expr(search_expr, &li))
726 /* Convert from /var/log/sudo-sessions/00/00/01/log to 000001 */
727 cp = logfile + strlen(session_dir) + 1;
738 /* Not an id, just use the iolog_file portion. */
739 cp[strlen(cp) - 4] = '\0';
742 printf("%s : %s : TTY=%s ; CWD=%s ; USER=%s ; ",
743 get_timestr(li.tstamp, 1), li.user, li.tty, li.cwd, li.runas_user);
745 printf("GROUP=%s ; ", li.runas_group);
746 printf("TSID=%s ; COMMAND=%s\n", idstr, li.cmd);
756 find_sessions(const char *dir, REGEX_T *re, const char *user, const char *tty)
763 char pathbuf[PATH_MAX];
767 error(1, _("unable to open %s"), dir);
769 /* XXX - would be faster to chdir and use relative names */
770 sdlen = strlcpy(pathbuf, dir, sizeof(pathbuf));
771 if (sdlen + 1 >= sizeof(pathbuf)) {
772 errno = ENAMETOOLONG;
773 error(1, "%s/", dir);
775 pathbuf[sdlen++] = '/';
776 pathbuf[sdlen] = '\0';
777 while ((dp = readdir(d)) != NULL) {
778 /* Skip "." and ".." */
779 if (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' ||
780 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
783 len = snprintf(&pathbuf[sdlen], sizeof(pathbuf) - sdlen,
784 "%s/log", dp->d_name);
785 if (len <= 0 || len >= sizeof(pathbuf) - sdlen) {
786 errno = ENAMETOOLONG;
787 error(1, "%s/%s/log", dir, dp->d_name);
790 /* Check for dir with a log file. */
791 if (lstat(pathbuf, &sb) == 0 && S_ISREG(sb.st_mode)) {
792 list_session(pathbuf, re, user, tty);
794 /* Strip off "/log" and recurse if a dir. */
795 pathbuf[sdlen + len - 4] = '\0';
796 if (lstat(pathbuf, &sb) == 0 && S_ISDIR(sb.st_mode))
797 find_sessions(pathbuf, re, user, tty);
806 list_sessions(int argc, char **argv, const char *pattern, const char *user,
809 REGEX_T rebuf, *re = NULL;
811 /* Parse search expression if present */
812 parse_expr(&search_expr, argv);
818 if (regcomp(re, pattern, REG_EXTENDED|REG_NOSUB) != 0)
819 errorx(1, _("invalid regex: %s"), pattern);
822 re = (char *) pattern;
823 #endif /* HAVE_REGCOMP */
825 return find_sessions(session_dir, re, user, tty);
829 * Check input for ' ', '<', '>'
833 check_input(int ttyfd, double *speed)
836 int nready, paused = 0;
841 fdsr = (fd_set *)emalloc2(howmany(ttyfd + 1, NFDBITS), sizeof(fd_mask));
848 nready = select(ttyfd + 1, fdsr, NULL, NULL, paused ? NULL : &tv);
851 n = read(ttyfd, &ch, 1);
874 * Parse a timing line, which is formatted as:
875 * index sleep_time num_bytes
876 * Where index is IOFD_*, sleep_time is the number of seconds to sleep
877 * before writing the data and num_bytes is the number of bytes to output.
878 * Returns 1 on success and 0 on failure.
881 parse_timing(buf, decimal, idx, seconds, nbytes)
894 ul = strtoul(buf, &ep, 10);
898 for (cp = ep + 1; isspace((unsigned char) *cp); cp++)
902 * Parse number of seconds. Sudo logs timing data in the C locale
903 * but this may not match the current locale so we cannot use strtod().
904 * Furthermore, sudo < 1.7.4 logged with the user's locale so we need
905 * to be able to parse those logs too.
908 l = strtol(cp, &ep, 10);
909 if ((errno == ERANGE && (l == LONG_MAX || l == LONG_MIN)) ||
910 l < 0 || l > INT_MAX ||
911 (*ep != '.' && strncmp(ep, decimal, strlen(decimal)) != 0)) {
914 *seconds = (double)l;
915 cp = ep + (*ep == '.' ? 1 : strlen(decimal));
917 while (isdigit((unsigned char) *cp)) {
918 fract += (*cp - '0') / d;
923 while (isspace((unsigned char) *cp))
927 ul = strtoul(cp, &ep, 10);
928 if (errno == ERANGE && ul == ULONG_MAX)
930 *nbytes = (size_t)ul;
940 fprintf(fatal ? stderr : stdout,
941 _("usage: %s [-h] [-d directory] [-m max_wait] [-s speed_factor] ID\n"),
943 fprintf(fatal ? stderr : stdout,
944 _("usage: %s [-h] [-d directory] -l [search expression]\n"),
953 (void) printf(_("%s - replay sudo session logs\n\n"), getprogname());
955 (void) puts(_("\nOptions:\n"
956 " -d directory specify directory for session logs\n"
957 " -f filter specify which I/O type to display\n"
958 " -h display help message and exit\n"
959 " -l [expression] list available session IDs that match expression\n"
960 " -m max_wait max number of seconds to wait between events\n"
961 " -s speed_factor speed up or slow down output\n"
962 " -V display version information and exit"));
967 * Cleanup hook for error()/errorx()
972 term_restore(STDIN_FILENO, 0);
974 kill(getpid(), signo);