2 * Copyright (c) 1994-1996, 1998-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.
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 */
43 #endif /* HAVE_STRING_H */
46 #endif /* HAVE_STRINGS_H */
49 #endif /* HAVE_UNISTD_H */
52 #endif /* HAVE_SETLOCALE */
53 #ifdef HAVE_NL_LANGINFO
54 # include <langinfo.h>
55 #endif /* HAVE_NL_LANGINFO */
65 static void do_syslog __P((int, char *));
66 static void do_logfile __P((char *));
67 static void send_mail __P((const char *fmt, ...));
68 static int should_mail __P((int));
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.
141 #ifdef HAVE_SETLOCALE
142 const char *old_locale = estrdup(setlocale(LC_ALL, NULL));
143 if (!setlocale(LC_ALL, def_sudoers_locale))
144 setlocale(LC_ALL, "C");
145 #endif /* HAVE_SETLOCALE */
148 * Log the full line, breaking into multiple syslog(3) calls if necessary
151 maxlen = MAXSYSLOGLEN - (sizeof(FMT_FIRST) - 6 + strlen(user_name));
152 for (p = msg; *p != '\0'; ) {
156 * Break up the line into what will fit on one syslog(3) line
157 * Try to avoid breaking words into several lines if possible.
159 tmp = memrchr(p, ' ', maxlen);
163 /* NULL terminate line, but save the char to restore later */
167 mysyslog(pri, fmt, user_name, p);
169 *tmp = save; /* restore saved character */
171 /* Advance p and eliminate leading whitespace */
172 for (p = tmp; *p == ' '; p++)
175 mysyslog(pri, fmt, user_name, p);
179 maxlen = MAXSYSLOGLEN - (sizeof(FMT_CONTD) - 6 + strlen(user_name));
182 #ifdef HAVE_SETLOCALE
183 setlocale(LC_ALL, old_locale);
184 efree((void *)old_locale);
185 #endif /* HAVE_SETLOCALE */
193 char *beg, *oldend, *end;
198 oldmask = umask(077);
199 maxlen = def_loglinelen > 0 ? def_loglinelen : 0;
200 fp = fopen(def_logfile, "a");
201 (void) umask(oldmask);
203 send_mail("Can't open log file: %s: %s", def_logfile, strerror(errno));
204 } else if (!lock_file(fileno(fp), SUDO_LOCK)) {
205 send_mail("Can't lock log file: %s: %s", def_logfile, strerror(errno));
209 #ifdef HAVE_SETLOCALE
210 const char *old_locale = estrdup(setlocale(LC_ALL, NULL));
211 if (!setlocale(LC_ALL, def_sudoers_locale))
212 setlocale(LC_ALL, "C");
213 #endif /* HAVE_SETLOCALE */
216 if (def_loglinelen == 0) {
217 /* Don't pretty-print long log file lines (hard to grep) */
219 (void) fprintf(fp, "%s : %s : HOST=%s : %s\n",
220 get_timestr(now, def_log_year), user_name, user_shost, msg);
222 (void) fprintf(fp, "%s : %s : %s\n",
223 get_timestr(now, def_log_year), user_name, msg);
226 easprintf(&full_line, "%s : %s : HOST=%s : %s",
227 get_timestr(now, def_log_year), user_name, user_shost, msg);
229 easprintf(&full_line, "%s : %s : %s",
230 get_timestr(now, def_log_year), user_name, msg);
233 * Print out full_line with word wrap
235 beg = end = full_line;
238 end = strchr(oldend, ' ');
240 if (maxlen > 0 && end) {
242 if (strlen(beg) > maxlen) {
243 /* too far, need to back up & print the line */
245 if (beg == (char *)full_line)
246 maxlen -= 4; /* don't indent first line */
255 (void) fprintf(fp, "%s\n ", beg);
258 (void) fprintf(fp, "%s\n ", beg);
261 /* reset beg to point to the start of the new substr */
266 /* we still have room */
270 /* remove leading whitespace */
275 (void) fprintf(fp, "%s\n", beg);
276 beg = NULL; /* exit condition */
282 (void) lock_file(fileno(fp), SUDO_UNLOCK);
285 #ifdef HAVE_SETLOCALE
286 setlocale(LC_ALL, old_locale);
287 efree((void *)old_locale);
288 #endif /* HAVE_SETLOCALE */
293 * Log and mail the denial message, optionally informing the user.
296 log_denial(status, inform_user)
303 /* Set error message. */
304 if (ISSET(status, FLAG_NO_USER))
305 message = "user NOT in sudoers";
306 else if (ISSET(status, FLAG_NO_HOST))
307 message = "user NOT authorized on host";
309 message = "command not allowed";
311 logline = new_logline(message, 0);
313 if (should_mail(status))
314 send_mail("%s", logline); /* send mail based on status */
316 /* Inform the user if they failed to authenticate. */
318 if (ISSET(status, FLAG_NO_USER))
319 (void) fprintf(stderr, "%s is not in the sudoers file. %s",
320 user_name, "This incident will be reported.\n");
321 else if (ISSET(status, FLAG_NO_HOST))
322 (void) fprintf(stderr, "%s is not allowed to run sudo on %s. %s",
323 user_name, user_shost, "This incident will be reported.\n");
324 else if (ISSET(status, FLAG_NO_CHECK))
325 (void) fprintf(stderr, "Sorry, user %s may not run sudo on %s.\n",
326 user_name, user_shost);
328 (void) fprintf(stderr,
329 "Sorry, user %s is not allowed to execute '%s%s%s' as %s%s%s on %s.\n",
330 user_name, user_cmnd, user_args ? " " : "",
331 user_args ? user_args : "",
332 list_pw ? list_pw->pw_name : runas_pw ?
333 runas_pw->pw_name : user_name, runas_gr ? ":" : "",
334 runas_gr ? runas_gr->gr_name : "", user_host);
338 * Log via syslog and/or a file.
341 do_syslog(def_syslog_badpri, logline);
349 * Log and potentially mail the allowed command.
357 logline = new_logline(NULL, 0);
359 if (should_mail(status))
360 send_mail("%s", logline); /* send mail based on status */
363 * Log via syslog and/or a file.
366 do_syslog(def_syslog_goodpri, logline);
375 log_error(int flags, const char *fmt, ...)
377 log_error(flags, fmt, va_alist)
393 /* Become root if we are not already to avoid user interference */
394 set_perms(PERM_ROOT|PERM_NOEXIT);
396 /* Expand printf-style format + args. */
397 evasprintf(&message, fmt, ap);
400 if (ISSET(flags, MSG_ONLY))
403 logline = new_logline(message, ISSET(flags, USE_ERRNO) ? serrno : 0);
408 if (!ISSET(flags, NO_STDERR)) {
409 if (ISSET(flags, USE_ERRNO))
410 warning("%s", message);
412 warningx("%s", message);
414 if (logline != message)
418 * Send a copy of the error via mail.
420 if (!ISSET(flags, NO_MAIL))
421 send_mail("%s", logline);
424 * Log to syslog and/or a file.
427 do_syslog(def_syslog_badpri, logline);
433 if (!ISSET(flags, NO_EXIT)) {
439 #define MAX_MAILFLAGS 63
442 * Send a message to MAILTO user
446 send_mail(const char *fmt, ...)
448 send_mail(fmt, va_alist)
455 int fd, pfd[2], status;
459 #ifndef NO_ROOT_MAILER
460 static char *root_envp[] = {
462 "PATH=/usr/bin:/bin:/usr/sbin:/sbin",
468 #endif /* NO_ROOT_MAILER */
470 /* Just return if mailer is disabled. */
471 if (!def_mailerpath || !def_mailto)
474 /* Fork and return, child will daemonize. */
475 switch (pid = fork()) {
478 error(1, "cannot fork");
482 switch (pid = fork()) {
485 mysyslog(LOG_ERR, "cannot fork: %m");
488 /* Grandchild continues below. */
491 /* Parent will wait for us. */
499 rv = waitpid(pid, &status, 0);
503 } while (rv == -1 && errno == EINTR);
507 /* Daemonize - disassociate from session/tty. */
510 if (chdir("/") == -1)
512 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0644)) != -1) {
513 (void) dup2(fd, STDIN_FILENO);
514 (void) dup2(fd, STDOUT_FILENO);
515 (void) dup2(fd, STDERR_FILENO);
518 #ifdef HAVE_SETLOCALE
519 if (!setlocale(LC_ALL, def_sudoers_locale)) {
520 setlocale(LC_ALL, "C");
521 efree(def_sudoers_locale);
522 def_sudoers_locale = estrdup("C");
524 #endif /* HAVE_SETLOCALE */
526 /* Close password, group and other fds so we don't leak. */
529 closefrom(STDERR_FILENO + 1);
531 /* Ignore SIGPIPE in case mailer exits prematurely (or is missing). */
532 zero_bytes(&sa, sizeof(sa));
533 sigemptyset(&sa.sa_mask);
534 sa.sa_flags = SA_INTERRUPT;
535 sa.sa_handler = SIG_IGN;
536 (void) sigaction(SIGPIPE, &sa, NULL);
538 if (pipe(pfd) == -1) {
539 mysyslog(LOG_ERR, "cannot open pipe: %m");
543 switch (pid = fork()) {
546 mysyslog(LOG_ERR, "cannot fork: %m");
551 char *argv[MAX_MAILFLAGS + 1];
552 char *mpath, *mflags;
555 /* Child, set stdin to output side of the pipe */
556 if (pfd[0] != STDIN_FILENO) {
557 if (dup2(pfd[0], STDIN_FILENO) == -1) {
558 mysyslog(LOG_ERR, "cannot dup stdin: %m");
561 (void) close(pfd[0]);
563 (void) close(pfd[1]);
565 /* Build up an argv based on the mailer path and flags */
566 mflags = estrdup(def_mailerflags);
567 mpath = estrdup(def_mailerpath);
568 if ((argv[0] = strrchr(mpath, ' ')))
574 if ((p = strtok(mflags, " \t"))) {
577 } while (++i < MAX_MAILFLAGS && (p = strtok(NULL, " \t")));
582 * Depending on the config, either run the mailer as root
583 * (so user cannot kill it) or as the user (for the paranoid).
585 #ifndef NO_ROOT_MAILER
586 set_perms(PERM_ROOT|PERM_NOEXIT);
587 execve(mpath, argv, root_envp);
589 set_perms(PERM_FULL_USER|PERM_NOEXIT);
591 #endif /* NO_ROOT_MAILER */
592 mysyslog(LOG_ERR, "cannot execute %s: %m", mpath);
598 (void) close(pfd[0]);
599 mail = fdopen(pfd[1], "w");
601 /* Pipes are all setup, send message. */
602 (void) fprintf(mail, "To: %s\nFrom: %s\nAuto-Submitted: %s\nSubject: ",
603 def_mailto, def_mailfrom ? def_mailfrom : user_name, "auto-generated");
604 for (p = def_mailsub; *p; p++) {
605 /* Expand escapes in the subject */
606 if (*p == '%' && *(p+1) != '%') {
609 (void) fputs(user_host, mail);
612 (void) fputs(user_name, mail);
619 (void) fputc(*p, mail);
622 #ifdef HAVE_NL_LANGINFO
623 if (strcmp(def_sudoers_locale, "C") != 0)
624 (void) fprintf(mail, "\nContent-Type: text/plain; charset=\"%s\"\nContent-Transfer-Encoding: 8bit", nl_langinfo(CODESET));
625 #endif /* HAVE_NL_LANGINFO */
627 (void) fprintf(mail, "\n\n%s : %s : %s : ", user_host,
628 get_timestr(time(NULL), def_log_year), user_name);
634 (void) vfprintf(mail, fmt, ap);
641 rv = waitpid(pid, &status, 0);
645 } while (rv == -1 && errno == EINTR);
650 * Determine whether we should send mail based on "status" and defaults options.
657 return def_mail_always || ISSET(status, VALIDATE_ERROR) ||
658 (def_mail_no_user && ISSET(status, FLAG_NO_USER)) ||
659 (def_mail_no_host && ISSET(status, FLAG_NO_HOST)) ||
660 (def_mail_no_perms && !ISSET(status, VALIDATE_OK));
663 #define LL_TTY_STR "TTY="
664 #define LL_CWD_STR "PWD=" /* XXX - should be CWD= */
665 #define LL_USER_STR "USER="
666 #define LL_GROUP_STR "GROUP="
667 #define LL_ENV_STR "ENV="
668 #define LL_CMND_STR "COMMAND="
669 #define LL_TSID_STR "TSID="
672 * Allocate and fill in a new logline.
675 new_logline(message, serrno)
685 * Compute line length
688 len += strlen(message) + 3;
690 errstr = strerror(serrno);
691 len += strlen(errstr) + 3;
693 len += sizeof(LL_TTY_STR) + 2 + strlen(user_tty);
694 len += sizeof(LL_CWD_STR) + 2 + strlen(user_cwd);
695 if (runas_pw != NULL)
696 len += sizeof(LL_USER_STR) + 2 + strlen(runas_pw->pw_name);
697 if (runas_gr != NULL)
698 len += sizeof(LL_GROUP_STR) + 2 + strlen(runas_gr->gr_name);
699 if (sudo_user.sessid[0] != '\0')
700 len += sizeof(LL_TSID_STR) + 2 + strlen(sudo_user.sessid);
701 if (sudo_user.env_vars != NULL) {
703 struct list_member *cur;
704 for (cur = sudo_user.env_vars; cur != NULL; cur = cur->next)
705 evlen += strlen(cur->value) + 1;
706 evstr = emalloc(evlen);
708 for (cur = sudo_user.env_vars; cur != NULL; cur = cur->next) {
709 strlcat(evstr, cur->value, evlen);
710 strlcat(evstr, " ", evlen); /* NOTE: last one will fail */
712 len += sizeof(LL_ENV_STR) + 2 + evlen;
714 /* Note: we log "sudo -l command arg ..." as "list command arg ..." */
715 len += sizeof(LL_CMND_STR) - 1 + strlen(user_cmnd);
716 if (ISSET(sudo_mode, MODE_CHECK))
717 len += sizeof("list ") - 1;
718 if (user_args != NULL)
719 len += strlen(user_args) + 1;
722 * Allocate and build up the line.
724 line = emalloc(++len);
727 if (message != NULL) {
728 if (strlcat(line, message, len) >= len ||
729 strlcat(line, errstr ? " : " : " ; ", len) >= len)
733 if (strlcat(line, errstr, len) >= len ||
734 strlcat(line, " ; ", len) >= len)
737 if (strlcat(line, LL_TTY_STR, len) >= len ||
738 strlcat(line, user_tty, len) >= len ||
739 strlcat(line, " ; ", len) >= len)
741 if (strlcat(line, LL_CWD_STR, len) >= len ||
742 strlcat(line, user_cwd, len) >= len ||
743 strlcat(line, " ; ", len) >= len)
745 if (runas_pw != NULL) {
746 if (strlcat(line, LL_USER_STR, len) >= len ||
747 strlcat(line, runas_pw->pw_name, len) >= len ||
748 strlcat(line, " ; ", len) >= len)
751 if (runas_gr != NULL) {
752 if (strlcat(line, LL_GROUP_STR, len) >= len ||
753 strlcat(line, runas_gr->gr_name, len) >= len ||
754 strlcat(line, " ; ", len) >= len)
757 if (sudo_user.sessid[0] != '\0') {
758 if (strlcat(line, LL_TSID_STR, len) >= len ||
759 strlcat(line, sudo_user.sessid, len) >= len ||
760 strlcat(line, " ; ", len) >= len)
764 if (strlcat(line, LL_ENV_STR, len) >= len ||
765 strlcat(line, evstr, len) >= len ||
766 strlcat(line, " ; ", len) >= len)
770 if (strlcat(line, LL_CMND_STR, len) >= len)
772 if (ISSET(sudo_mode, MODE_CHECK) && strlcat(line, "list ", len) >= len)
774 if (strlcat(line, user_cmnd, len) >= len)
776 if (user_args != NULL) {
777 if (strlcat(line, " ", len) >= len ||
778 strlcat(line, user_args, len) >= len)
784 errorx(1, "internal error: insufficient space for log line");