2 * Copyright (c) 1994-1996, 1998-2009 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.
16 * Sponsored in part by the Defense Advanced Research Projects
17 * Agency (DARPA) and Air Force Research Laboratory, Air Force
18 * Materiel Command, USAF, under agreement number F39502-99-1-0512.
27 #include <sys/types.h>
28 #include <sys/param.h>
30 #include <sys/ioctl.h>
40 #endif /* STDC_HEADERS */
44 # ifdef HAVE_STRINGS_H
47 #endif /* HAVE_STRING_H */
50 #endif /* HAVE_UNISTD_H */
61 __unused static const char rcsid[] = "$Sudo: logging.c,v 1.205 2009/05/25 12:02:41 millert Exp $";
64 static void do_syslog __P((int, char *));
65 static void do_logfile __P((char *));
66 static void send_mail __P((char *));
67 static int should_mail __P((int));
68 static char *get_timestr __P((void));
69 static void mysyslog __P((int, const char *, ...));
70 static char *new_logline __P((const char *, int));
72 #define MAXSYSLOGTRIES 16 /* num of retries for broken syslogs */
75 * We do an openlog(3)/closelog(3) for each message because some
76 * authentication methods (notably PAM) use syslog(3) for their
77 * own nefarious purposes and may call openlog(3) and closelog(3).
78 * Note that because we don't want to assume that all systems have
79 * vsyslog(3) (HP-UX doesn't) "%m" will not be expanded.
80 * Sadly this is a maze of #ifdefs.
84 mysyslog(int pri, const char *fmt, ...)
86 mysyslog(pri, fmt, va_alist)
95 char buf[MAXSYSLOGLEN+1];
103 #ifdef LOG_NFACILITIES
104 openlog("sudo", 0, def_syslog);
108 vsnprintf(buf, sizeof(buf), fmt, ap);
111 * Some versions of syslog(3) don't guarantee success and return
112 * an int (notably HP-UX < 10.0). So, if at first we don't succeed,
115 for (i = 0; i < MAXSYSLOGTRIES; i++)
116 if (syslog(pri, "%s", buf) == 0)
119 syslog(pri, "%s", buf);
120 #endif /* BROKEN_SYSLOG */
125 #define FMT_FIRST "%8s : %s"
126 #define FMT_CONTD "%8s : (command continued) %s"
129 * Log a message to syslog, pre-pending the username and splitting the
130 * message into parts if it is longer than MAXSYSLOGLEN.
142 * Log the full line, breaking into multiple syslog(3) calls if necessary
145 maxlen = MAXSYSLOGLEN - (sizeof(FMT_FIRST) - 6 + strlen(user_name));
146 for (p = msg; *p != '\0'; ) {
150 * Break up the line into what will fit on one syslog(3) line
151 * Try to avoid breaking words into several lines if possible.
153 tmp = memrchr(p, ' ', maxlen);
157 /* NULL terminate line, but save the char to restore later */
161 mysyslog(pri, fmt, user_name, p);
163 *tmp = save; /* restore saved character */
165 /* Advance p and eliminate leading whitespace */
166 for (p = tmp; *p == ' '; p++)
169 mysyslog(pri, fmt, user_name, p);
173 maxlen = MAXSYSLOGLEN - (sizeof(FMT_CONTD) - 6 + strlen(user_name));
182 char *beg, *oldend, *end;
187 oldmask = umask(077);
188 maxlen = def_loglinelen > 0 ? def_loglinelen : 0;
189 fp = fopen(def_logfile, "a");
190 (void) umask(oldmask);
192 easprintf(&full_line, "Can't open log file: %s: %s",
193 def_logfile, strerror(errno));
194 send_mail(full_line);
196 } else if (!lock_file(fileno(fp), SUDO_LOCK)) {
197 easprintf(&full_line, "Can't lock log file: %s: %s",
198 def_logfile, strerror(errno));
199 send_mail(full_line);
202 if (def_loglinelen == 0) {
203 /* Don't pretty-print long log file lines (hard to grep) */
205 (void) fprintf(fp, "%s : %s : HOST=%s : %s\n", get_timestr(),
206 user_name, user_shost, msg);
208 (void) fprintf(fp, "%s : %s : %s\n", get_timestr(),
212 easprintf(&full_line, "%s : %s : HOST=%s : %s", get_timestr(),
213 user_name, user_shost, msg);
215 easprintf(&full_line, "%s : %s : %s", get_timestr(),
219 * Print out full_line with word wrap
221 beg = end = full_line;
224 end = strchr(oldend, ' ');
226 if (maxlen > 0 && end) {
228 if (strlen(beg) > maxlen) {
229 /* too far, need to back up & print the line */
231 if (beg == (char *)full_line)
232 maxlen -= 4; /* don't indent first line */
241 (void) fprintf(fp, "%s\n ", beg);
244 (void) fprintf(fp, "%s\n ", beg);
247 /* reset beg to point to the start of the new substr */
252 /* we still have room */
256 /* remove leading whitespace */
261 (void) fprintf(fp, "%s\n", beg);
262 beg = NULL; /* exit condition */
268 (void) lock_file(fileno(fp), SUDO_UNLOCK);
274 * Log and mail the denial message, optionally informing the user.
277 log_denial(status, inform_user)
284 /* Set error message. */
285 if (ISSET(status, FLAG_NO_USER))
286 message = "user NOT in sudoers";
287 else if (ISSET(status, FLAG_NO_HOST))
288 message = "user NOT authorized on host";
290 message = "command not allowed";
292 logline = new_logline(message, 0);
294 if (should_mail(status))
295 send_mail(logline); /* send mail based on status */
297 /* Inform the user if they failed to authenticate. */
299 if (ISSET(status, FLAG_NO_USER))
300 (void) fprintf(stderr, "%s is not in the sudoers file. %s",
301 user_name, "This incident will be reported.\n");
302 else if (ISSET(status, FLAG_NO_HOST))
303 (void) fprintf(stderr, "%s is not allowed to run sudo on %s. %s",
304 user_name, user_shost, "This incident will be reported.\n");
305 else if (ISSET(status, FLAG_NO_CHECK))
306 (void) fprintf(stderr, "Sorry, user %s may not run sudo on %s.\n",
307 user_name, user_shost);
309 (void) fprintf(stderr,
310 "Sorry, user %s is not allowed to execute '%s%s%s' as %s%s%s on %s.\n",
311 user_name, user_cmnd, user_args ? " " : "",
312 user_args ? user_args : "",
313 list_pw ? list_pw->pw_name : runas_pw ?
314 runas_pw->pw_name : user_name, runas_gr ? ":" : "",
315 runas_gr ? runas_gr->gr_name : "", user_host);
319 * Log via syslog and/or a file.
322 do_syslog(def_syslog_badpri, logline);
330 * Log and potentially mail the allowed command.
338 logline = new_logline(NULL, 0);
340 if (should_mail(status))
341 send_mail(logline); /* send mail based on status */
344 * Log via syslog and/or a file.
347 do_syslog(def_syslog_goodpri, logline);
356 log_error(int flags, const char *fmt, ...)
358 log_error(flags, fmt, va_alist)
374 /* Become root if we are not already to avoid user interference */
375 set_perms(PERM_ROOT|PERM_NOEXIT);
377 /* Expand printf-style format + args. */
378 evasprintf(&message, fmt, ap);
381 if (ISSET(flags, MSG_ONLY))
384 logline = new_logline(message, ISSET(flags, USE_ERRNO) ? serrno : 0);
389 if (!ISSET(flags, NO_STDERR)) {
390 if (ISSET(flags, USE_ERRNO))
391 warning("%s", message);
393 warningx("%s", message);
395 if (logline != message)
399 * Send a copy of the error via mail.
401 if (!ISSET(flags, NO_MAIL))
405 * Log to syslog and/or a file.
408 do_syslog(def_syslog_badpri, logline);
414 if (!ISSET(flags, NO_EXIT)) {
420 #define MAX_MAILFLAGS 63
423 * Send a message to MAILTO user
431 int fd, pfd[2], status;
434 #ifndef NO_ROOT_MAILER
435 static char *root_envp[] = {
437 "PATH=/usr/bin:/bin",
445 /* Just return if mailer is disabled. */
446 if (!def_mailerpath || !def_mailto)
449 /* Fork and return, child will daemonize. */
450 switch (pid = fork()) {
453 error(1, "cannot fork");
457 switch (pid = fork()) {
460 mysyslog(LOG_ERR, "cannot fork: %m");
463 /* Grandchild continues below. */
466 /* Parent will wait for us. */
474 rv = waitpid(pid, &status, 0);
478 } while (rv == -1 && errno == EINTR);
482 /* Daemonize - disassociate from session/tty. */
489 if ((fd = open(_PATH_TTY, O_RDWR, 0644)) != -1) {
490 ioctl(fd, TIOCNOTTY, NULL);
496 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0644)) != -1) {
497 (void) dup2(fd, STDIN_FILENO);
498 (void) dup2(fd, STDOUT_FILENO);
499 (void) dup2(fd, STDERR_FILENO);
502 /* Close password, group and other fds so we don't leak. */
505 closefrom(STDERR_FILENO + 1);
507 /* Ignore SIGPIPE in case mailer exits prematurely (or is missing). */
508 zero_bytes(&sa, sizeof(sa));
509 sigemptyset(&sa.sa_mask);
511 sa.sa_handler = SIG_IGN;
512 (void) sigaction(SIGPIPE, &sa, NULL);
514 if (pipe(pfd) == -1) {
515 mysyslog(LOG_ERR, "cannot open pipe: %m");
519 switch (pid = fork()) {
522 mysyslog(LOG_ERR, "cannot fork: %m");
527 char *argv[MAX_MAILFLAGS + 1];
528 char *mpath, *mflags;
531 /* Child, set stdin to output side of the pipe */
532 if (pfd[0] != STDIN_FILENO) {
533 (void) dup2(pfd[0], STDIN_FILENO);
534 (void) close(pfd[0]);
536 (void) close(pfd[1]);
538 /* Build up an argv based the mailer path and flags */
539 mflags = estrdup(def_mailerflags);
540 mpath = estrdup(def_mailerpath);
541 if ((argv[0] = strrchr(mpath, ' ')))
547 if ((p = strtok(mflags, " \t"))) {
550 } while (++i < MAX_MAILFLAGS && (p = strtok(NULL, " \t")));
555 * Depending on the config, either run the mailer as root
556 * (so user cannot kill it) or as the user (for the paranoid).
558 #ifndef NO_ROOT_MAILER
559 set_perms(PERM_ROOT|PERM_NOEXIT);
560 execve(mpath, argv, root_envp);
562 set_perms(PERM_FULL_USER|PERM_NOEXIT);
564 #endif /* NO_ROOT_MAILER */
565 mysyslog(LOG_ERR, "cannot execute %s: %m", mpath);
571 (void) close(pfd[0]);
572 mail = fdopen(pfd[1], "w");
574 /* Pipes are all setup, send message. */
575 (void) fprintf(mail, "To: %s\nFrom: %s\nAuto-Submitted: %s\nSubject: ",
576 def_mailto, def_mailfrom ? def_mailfrom : user_name, "auto-generated");
577 for (p = def_mailsub; *p; p++) {
578 /* Expand escapes in the subject */
579 if (*p == '%' && *(p+1) != '%') {
582 (void) fputs(user_host, mail);
585 (void) fputs(user_name, mail);
592 (void) fputc(*p, mail);
594 (void) fprintf(mail, "\n\n%s : %s : %s : %s\n\n", user_host,
595 get_timestr(), user_name, line);
599 rv = waitpid(pid, &status, 0);
603 } while (rv == -1 && errno == EINTR);
608 * Determine whether we should send mail based on "status" and defaults options.
615 return(def_mail_always || ISSET(status, VALIDATE_ERROR) ||
616 (def_mail_no_user && ISSET(status, FLAG_NO_USER)) ||
617 (def_mail_no_host && ISSET(status, FLAG_NO_HOST)) ||
618 (def_mail_no_perms && !ISSET(status, VALIDATE_OK)));
622 * Return an ascii string with the current date + time
623 * Uses strftime() if available, else falls back to ctime().
629 time_t now = time((time_t) 0);
631 static char buf[128];
634 timeptr = localtime(&now);
640 /* strftime() does not guarantee to NUL-terminate so we must check. */
641 buf[sizeof(buf) - 1] = '\0';
642 if (strftime(buf, sizeof(buf), s, timeptr) && buf[sizeof(buf) - 1] == '\0')
645 #endif /* HAVE_STRFTIME */
647 s = ctime(&now) + 4; /* skip day of the week */
649 s[20] = '\0'; /* avoid the newline */
651 s[15] = '\0'; /* don't care about year */
656 #define LL_TTY_STR "TTY="
657 #define LL_CWD_STR "PWD=" /* XXX - should be CWD= */
658 #define LL_USER_STR "USER="
659 #define LL_GROUP_STR "GROUP="
660 #define LL_ENV_STR "ENV="
661 #define LL_CMND_STR "COMMAND="
664 * Allocate and fill in a new logline.
667 new_logline(message, serrno)
677 * Compute line length
680 len += strlen(message) + 3;
682 errstr = strerror(serrno);
683 len += strlen(errstr) + 3;
685 len += sizeof(LL_TTY_STR) + 2 + strlen(user_tty);
686 len += sizeof(LL_CWD_STR) + 2 + strlen(user_cwd);
687 if (runas_pw != NULL)
688 len += sizeof(LL_USER_STR) + 2 + strlen(runas_pw->pw_name);
689 if (runas_gr != NULL)
690 len += sizeof(LL_GROUP_STR) + 2 + strlen(runas_gr->gr_name);
691 if (sudo_user.env_vars != NULL) {
693 struct list_member *cur;
694 for (cur = sudo_user.env_vars; cur != NULL; cur = cur->next)
695 evlen += strlen(cur->value) + 1;
696 evstr = emalloc(evlen);
698 for (cur = sudo_user.env_vars; cur != NULL; cur = cur->next) {
699 strlcat(evstr, cur->value, evlen);
700 strlcat(evstr, " ", evlen); /* NOTE: last one will fail */
702 len += sizeof(LL_ENV_STR) + 2 + evlen;
704 len += sizeof(LL_CMND_STR) - 1 + strlen(user_cmnd);
705 if (user_args != NULL)
706 len += strlen(user_args) + 1;
709 * Allocate and build up the line.
711 line = emalloc(++len);
714 if (message != NULL) {
715 if (strlcat(line, message, len) >= len ||
716 strlcat(line, errstr ? " : " : " ; ", len) >= len)
720 if (strlcat(line, errstr, len) >= len ||
721 strlcat(line, " ; ", len) >= len)
724 if (strlcat(line, LL_TTY_STR, len) >= len ||
725 strlcat(line, user_tty, len) >= len ||
726 strlcat(line, " ; ", len) >= len)
728 if (strlcat(line, LL_CWD_STR, len) >= len ||
729 strlcat(line, user_cwd, len) >= len ||
730 strlcat(line, " ; ", len) >= len)
732 if (runas_pw != NULL) {
733 if (strlcat(line, LL_USER_STR, len) >= len ||
734 strlcat(line, runas_pw->pw_name, len) >= len ||
735 strlcat(line, " ; ", len) >= len)
738 if (runas_gr != NULL) {
739 if (strlcat(line, LL_GROUP_STR, len) >= len ||
740 strlcat(line, runas_gr->gr_name, len) >= len ||
741 strlcat(line, " ; ", len) >= len)
745 if (strlcat(line, LL_ENV_STR, len) >= len ||
746 strlcat(line, evstr, len) >= len ||
747 strlcat(line, " ; ", len) >= len)
751 if (strlcat(line, LL_CMND_STR, len) >= len ||
752 strlcat(line, user_cmnd, len) >= len)
754 if (user_args != NULL) {
755 if (strlcat(line, " ", len) >= len ||
756 strlcat(line, user_args, len) >= len)
762 errorx(1, "internal error: insufficient space for log line");