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 */
126 * Log a message to syslog, pre-pending the username and splitting the
127 * message into parts if it is longer than MAXSYSLOGLEN.
137 const char *fmt_first = "%8s : %s";
138 const char *fmt_contd = "%8s : (command continued) %s";
141 * Log the full line, breaking into multiple syslog(3) calls if necessary
144 maxlen = MAXSYSLOGLEN - (sizeof(fmt_first) - 6 + strlen(user_name));
145 for (p = msg; *p != '\0'; ) {
149 * Break up the line into what will fit on one syslog(3) line
150 * Try to avoid breaking words into several lines if possible.
152 tmp = memrchr(p, ' ', maxlen);
156 /* NULL terminate line, but save the char to restore later */
160 mysyslog(pri, fmt, user_name, p);
162 *tmp = save; /* restore saved character */
164 /* Advance p and eliminate leading whitespace */
165 for (p = tmp; *p == ' '; p++)
168 mysyslog(pri, fmt, user_name, p);
172 maxlen = MAXSYSLOGLEN - (sizeof(fmt_contd) - 6 + strlen(user_name));
181 char *beg, *oldend, *end;
186 oldmask = umask(077);
187 maxlen = def_loglinelen > 0 ? def_loglinelen : 0;
188 fp = fopen(def_logfile, "a");
189 (void) umask(oldmask);
191 easprintf(&full_line, "Can't open log file: %s: %s",
192 def_logfile, strerror(errno));
193 send_mail(full_line);
195 } else if (!lock_file(fileno(fp), SUDO_LOCK)) {
196 easprintf(&full_line, "Can't lock log file: %s: %s",
197 def_logfile, strerror(errno));
198 send_mail(full_line);
201 if (def_loglinelen == 0) {
202 /* Don't pretty-print long log file lines (hard to grep) */
204 (void) fprintf(fp, "%s : %s : HOST=%s : %s\n", get_timestr(),
205 user_name, user_shost, msg);
207 (void) fprintf(fp, "%s : %s : %s\n", get_timestr(),
211 easprintf(&full_line, "%s : %s : HOST=%s : %s", get_timestr(),
212 user_name, user_shost, msg);
214 easprintf(&full_line, "%s : %s : %s", get_timestr(),
218 * Print out full_line with word wrap
220 beg = end = full_line;
223 end = strchr(oldend, ' ');
225 if (maxlen > 0 && end) {
227 if (strlen(beg) > maxlen) {
228 /* too far, need to back up & print the line */
230 if (beg == (char *)full_line)
231 maxlen -= 4; /* don't indent first line */
240 (void) fprintf(fp, "%s\n ", beg);
243 (void) fprintf(fp, "%s\n ", beg);
246 /* reset beg to point to the start of the new substr */
251 /* we still have room */
255 /* remove leading whitespace */
260 (void) fprintf(fp, "%s\n", beg);
261 beg = NULL; /* exit condition */
267 (void) lock_file(fileno(fp), SUDO_UNLOCK);
273 * Log and mail the denial message, optionally informing the user.
276 log_denial(status, inform_user)
283 /* Set error message. */
284 if (ISSET(status, FLAG_NO_USER))
285 message = "user NOT in sudoers";
286 else if (ISSET(status, FLAG_NO_HOST))
287 message = "user NOT authorized on host";
289 message = "command not allowed";
291 logline = new_logline(message, 0);
293 if (should_mail(status))
294 send_mail(logline); /* send mail based on status */
296 /* Inform the user if they failed to authenticate. */
298 if (ISSET(status, FLAG_NO_USER))
299 (void) fprintf(stderr, "%s is not in the sudoers file. %s",
300 user_name, "This incident will be reported.\n");
301 else if (ISSET(status, FLAG_NO_HOST))
302 (void) fprintf(stderr, "%s is not allowed to run sudo on %s. %s",
303 user_name, user_shost, "This incident will be reported.\n");
304 else if (ISSET(status, FLAG_NO_CHECK))
305 (void) fprintf(stderr, "Sorry, user %s may not run sudo on %s.\n",
306 user_name, user_shost);
308 (void) fprintf(stderr,
309 "Sorry, user %s is not allowed to execute '%s%s%s' as %s%s%s on %s.\n",
310 user_name, user_cmnd, user_args ? " " : "",
311 user_args ? user_args : "",
312 list_pw ? list_pw->pw_name : runas_pw ?
313 runas_pw->pw_name : user_name, runas_gr ? ":" : "",
314 runas_gr ? runas_gr->gr_name : "", user_host);
318 * Log via syslog and/or a file.
321 do_syslog(def_syslog_badpri, logline);
329 * Log and potentially mail the allowed command.
337 logline = new_logline(NULL, 0);
339 if (should_mail(status))
340 send_mail(logline); /* send mail based on status */
343 * Log via syslog and/or a file.
346 do_syslog(def_syslog_goodpri, logline);
355 log_error(int flags, const char *fmt, ...)
357 log_error(flags, fmt, va_alist)
373 /* Become root if we are not already to avoid user interference */
374 set_perms(PERM_ROOT|PERM_NOEXIT);
376 /* Expand printf-style format + args. */
377 evasprintf(&message, fmt, ap);
380 if (ISSET(flags, MSG_ONLY))
383 logline = new_logline(message, ISSET(flags, USE_ERRNO) ? serrno : 0);
388 if (!ISSET(flags, NO_STDERR)) {
389 if (ISSET(flags, USE_ERRNO))
390 warning("%s", message);
392 warningx("%s", message);
397 * Send a copy of the error via mail.
399 if (!ISSET(flags, NO_MAIL))
403 * Log to syslog and/or a file.
406 do_syslog(def_syslog_badpri, logline);
410 if (logline != message)
413 if (!ISSET(flags, NO_EXIT)) {
419 #define MAX_MAILFLAGS 63
422 * Send a message to MAILTO user
430 int fd, pfd[2], status;
433 #ifndef NO_ROOT_MAILER
434 static char *root_envp[] = {
436 "PATH=/usr/bin:/bin",
444 /* Just return if mailer is disabled. */
445 if (!def_mailerpath || !def_mailto)
448 /* Fork and return, child will daemonize. */
449 switch (pid = fork()) {
452 error(1, "cannot fork");
456 switch (pid = fork()) {
459 mysyslog(LOG_ERR, "cannot fork: %m");
462 /* Grandchild continues below. */
465 /* Parent will wait for us. */
473 rv = waitpid(pid, &status, 0);
477 } while (rv == -1 && errno == EINTR);
481 /* Daemonize - disassociate from session/tty. */
488 if ((fd = open(_PATH_TTY, O_RDWR, 0644)) != -1) {
489 ioctl(fd, TIOCNOTTY, NULL);
495 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0644)) != -1) {
496 (void) dup2(fd, STDIN_FILENO);
497 (void) dup2(fd, STDOUT_FILENO);
498 (void) dup2(fd, STDERR_FILENO);
501 /* Close password, group and other fds so we don't leak. */
504 closefrom(STDERR_FILENO + 1);
506 /* Ignore SIGPIPE in case mailer exits prematurely (or is missing). */
507 zero_bytes(&sa, sizeof(sa));
508 sigemptyset(&sa.sa_mask);
510 sa.sa_handler = SIG_IGN;
511 (void) sigaction(SIGPIPE, &sa, NULL);
513 if (pipe(pfd) == -1) {
514 mysyslog(LOG_ERR, "cannot open pipe: %m");
518 switch (pid = fork()) {
521 mysyslog(LOG_ERR, "cannot fork: %m");
526 char *argv[MAX_MAILFLAGS + 1];
527 char *mpath, *mflags;
530 /* Child, set stdin to output side of the pipe */
531 if (pfd[0] != STDIN_FILENO) {
532 (void) dup2(pfd[0], STDIN_FILENO);
533 (void) close(pfd[0]);
535 (void) close(pfd[1]);
537 /* Build up an argv based the mailer path and flags */
538 mflags = estrdup(def_mailerflags);
539 mpath = estrdup(def_mailerpath);
540 if ((argv[0] = strrchr(mpath, ' ')))
546 if ((p = strtok(mflags, " \t"))) {
549 } while (++i < MAX_MAILFLAGS && (p = strtok(NULL, " \t")));
554 * Depending on the config, either run the mailer as root
555 * (so user cannot kill it) or as the user (for the paranoid).
557 #ifndef NO_ROOT_MAILER
558 set_perms(PERM_ROOT|PERM_NOEXIT);
559 execve(mpath, argv, root_envp);
561 set_perms(PERM_FULL_USER|PERM_NOEXIT);
563 #endif /* NO_ROOT_MAILER */
564 mysyslog(LOG_ERR, "cannot execute %s: %m", mpath);
570 (void) close(pfd[0]);
571 mail = fdopen(pfd[1], "w");
573 /* Pipes are all setup, send message. */
574 (void) fprintf(mail, "To: %s\nFrom: %s\nAuto-Submitted: %s\nSubject: ",
575 def_mailto, def_mailfrom ? def_mailfrom : user_name, "auto-generated");
576 for (p = def_mailsub; *p; p++) {
577 /* Expand escapes in the subject */
578 if (*p == '%' && *(p+1) != '%') {
581 (void) fputs(user_host, mail);
584 (void) fputs(user_name, mail);
591 (void) fputc(*p, mail);
593 (void) fprintf(mail, "\n\n%s : %s : %s : %s\n\n", user_host,
594 get_timestr(), user_name, line);
598 rv = waitpid(pid, &status, 0);
602 } while (rv == -1 && errno == EINTR);
607 * Determine whether we should send mail based on "status" and defaults options.
614 return(def_mail_always || ISSET(status, VALIDATE_ERROR) ||
615 (def_mail_no_user && ISSET(status, FLAG_NO_USER)) ||
616 (def_mail_no_host && ISSET(status, FLAG_NO_HOST)) ||
617 (def_mail_no_perms && !ISSET(status, VALIDATE_OK)));
621 * Return an ascii string with the current date + time
622 * Uses strftime() if available, else falls back to ctime().
628 time_t now = time((time_t) 0);
630 static char buf[128];
633 timeptr = localtime(&now);
639 /* strftime() does not guarantee to NUL-terminate so we must check. */
640 buf[sizeof(buf) - 1] = '\0';
641 if (strftime(buf, sizeof(buf), s, timeptr) && buf[sizeof(buf) - 1] == '\0')
644 #endif /* HAVE_STRFTIME */
646 s = ctime(&now) + 4; /* skip day of the week */
648 s[20] = '\0'; /* avoid the newline */
650 s[15] = '\0'; /* don't care about year */
655 #define LL_TTY_STR "TTY="
656 #define LL_CWD_STR "PWD=" /* XXX - should be CWD= */
657 #define LL_USER_STR "USER="
658 #define LL_GROUP_STR "GROUP="
659 #define LL_ENV_STR "ENV="
660 #define LL_CMND_STR "COMMAND="
663 * Allocate and fill in a new logline.
666 new_logline(message, serrno)
676 * Compute line length
679 len += strlen(message) + 3;
681 errstr = strerror(serrno);
682 len += strlen(errstr) + 3;
684 len += sizeof(LL_TTY_STR) + 2 + strlen(user_tty);
685 len += sizeof(LL_CWD_STR) + 2 + strlen(user_cwd);
686 if (runas_pw != NULL)
687 len += sizeof(LL_USER_STR) + 2 + strlen(runas_pw->pw_name);
688 if (runas_gr != NULL)
689 len += sizeof(LL_GROUP_STR) + 2 + strlen(runas_gr->gr_name);
690 if (sudo_user.env_vars != NULL) {
692 struct list_member *cur;
693 for (cur = sudo_user.env_vars; cur != NULL; cur = cur->next)
694 evlen += strlen(cur->value) + 1;
695 evstr = emalloc(evlen);
697 for (cur = sudo_user.env_vars; cur != NULL; cur = cur->next) {
698 strlcat(evstr, cur->value, evlen);
699 strlcat(evstr, " ", evlen); /* NOTE: last one will fail */
701 len += sizeof(LL_ENV_STR) + 2 + evlen;
703 len += sizeof(LL_CMND_STR) - 1 + strlen(user_cmnd);
704 if (user_args != NULL)
705 len += strlen(user_args) + 1;
708 * Allocate and build up the line.
710 line = emalloc(++len);
713 if (message != NULL) {
714 if (strlcat(line, message, len) >= len ||
715 strlcat(line, errstr ? " : " : " ; ", len) >= len)
719 if (strlcat(line, errstr, len) >= len ||
720 strlcat(line, " ; ", len) >= len)
723 if (strlcat(line, LL_TTY_STR, len) >= len ||
724 strlcat(line, user_tty, len) >= len ||
725 strlcat(line, " ; ", len) >= len)
727 if (strlcat(line, LL_CWD_STR, len) >= len ||
728 strlcat(line, user_cwd, len) >= len ||
729 strlcat(line, " ; ", len) >= len)
731 if (runas_pw != NULL) {
732 if (strlcat(line, LL_USER_STR, len) >= len ||
733 strlcat(line, runas_pw->pw_name, len) >= len ||
734 strlcat(line, " ; ", len) >= len)
737 if (runas_gr != NULL) {
738 if (strlcat(line, LL_GROUP_STR, len) >= len ||
739 strlcat(line, runas_gr->gr_name, len) >= len ||
740 strlcat(line, " ; ", len) >= len)
744 if (strlcat(line, LL_ENV_STR, len) >= len ||
745 strlcat(line, evstr, len) >= len ||
746 strlcat(line, " ; ", len) >= len)
750 if (strlcat(line, LL_CMND_STR, len) >= len ||
751 strlcat(line, user_cmnd, len) >= len)
753 if (user_args != NULL) {
754 if (strlcat(line, " ", len) >= len ||
755 strlcat(line, user_args, len) >= len)
761 errorx(1, "internal error: insufficient space for log line");