2 * Copyright (c) 1994-1996, 1998-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.
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 */
67 static void do_syslog(int, char *);
68 static void do_logfile(char *);
69 static void send_mail(const char *fmt, ...);
70 static int should_mail(int);
71 static void mysyslog(int, const char *, ...);
72 static char *new_logline(const char *, int);
74 extern sigjmp_buf error_jmp;
76 extern char **NewArgv; /* XXX - for auditing */
78 #define MAXSYSLOGTRIES 16 /* num of retries for broken syslogs */
81 * We do an openlog(3)/closelog(3) for each message because some
82 * authentication methods (notably PAM) use syslog(3) for their
83 * own nefarious purposes and may call openlog(3) and closelog(3).
84 * Note that because we don't want to assume that all systems have
85 * vsyslog(3) (HP-UX doesn't) "%m" will not be expanded.
86 * Sadly this is a maze of #ifdefs.
89 mysyslog(int pri, const char *fmt, ...)
94 char buf[MAXSYSLOGLEN+1];
96 debug_decl(mysyslog, SUDO_DEBUG_LOGGING)
99 #ifdef LOG_NFACILITIES
100 openlog("sudo", 0, def_syslog);
104 vsnprintf(buf, sizeof(buf), fmt, ap);
107 * Some versions of syslog(3) don't guarantee success and return
108 * an int (notably HP-UX < 10.0). So, if at first we don't succeed,
111 for (i = 0; i < MAXSYSLOGTRIES; i++)
112 if (syslog(pri, "%s", buf) == 0)
115 syslog(pri, "%s", buf);
116 #endif /* BROKEN_SYSLOG */
122 #define FMT_FIRST "%8s : %s"
123 #define FMT_CONTD "%8s : (command continued) %s"
126 * Log a message to syslog, pre-pending the username and splitting the
127 * message into parts if it is longer than MAXSYSLOGLEN.
130 do_syslog(int pri, char *msg)
135 #ifdef HAVE_SETLOCALE
136 const char *old_locale = estrdup(setlocale(LC_ALL, NULL));
138 debug_decl(do_syslog, SUDO_DEBUG_LOGGING)
140 #ifdef HAVE_SETLOCALE
141 if (!setlocale(LC_ALL, def_sudoers_locale))
142 setlocale(LC_ALL, "C");
143 #endif /* HAVE_SETLOCALE */
146 * Log the full line, breaking into multiple syslog(3) calls if necessary
149 maxlen = MAXSYSLOGLEN - (strlen(fmt) - 5 + strlen(user_name));
150 for (p = msg; *p != '\0'; ) {
154 * Break up the line into what will fit on one syslog(3) line
155 * Try to avoid breaking words into several lines if possible.
157 tmp = memrchr(p, ' ', maxlen);
161 /* NULL terminate line, but save the char to restore later */
165 mysyslog(pri, fmt, user_name, p);
167 *tmp = save; /* restore saved character */
169 /* Advance p and eliminate leading whitespace */
170 for (p = tmp; *p == ' '; p++)
173 mysyslog(pri, fmt, user_name, p);
177 maxlen = MAXSYSLOGLEN - (strlen(fmt) - 5 + strlen(user_name));
180 #ifdef HAVE_SETLOCALE
181 setlocale(LC_ALL, old_locale);
182 efree((void *)old_locale);
183 #endif /* HAVE_SETLOCALE */
189 do_logfile(char *msg)
196 debug_decl(do_logfile, SUDO_DEBUG_LOGGING)
198 oldmask = umask(077);
199 fp = fopen(def_logfile, "a");
200 (void) umask(oldmask);
202 send_mail(_("unable to open log file: %s: %s"),
203 def_logfile, strerror(errno));
204 } else if (!lock_file(fileno(fp), SUDO_LOCK)) {
205 send_mail(_("unable to lock log file: %s: %s"),
206 def_logfile, strerror(errno));
208 #ifdef HAVE_SETLOCALE
209 const char *old_locale = estrdup(setlocale(LC_ALL, NULL));
210 if (!setlocale(LC_ALL, def_sudoers_locale))
211 setlocale(LC_ALL, "C");
212 #endif /* HAVE_SETLOCALE */
215 if (def_loglinelen < sizeof(LOG_INDENT)) {
216 /* Don't pretty-print long log file lines (hard to grep) */
218 (void) fprintf(fp, "%s : %s : HOST=%s : %s\n",
219 get_timestr(now, def_log_year), user_name, user_shost, msg);
221 (void) fprintf(fp, "%s : %s : %s\n",
222 get_timestr(now, def_log_year), user_name, msg);
225 len = easprintf(&full_line, "%s : %s : HOST=%s : %s",
226 get_timestr(now, def_log_year), user_name, user_shost, msg);
228 len = easprintf(&full_line, "%s : %s : %s",
229 get_timestr(now, def_log_year), user_name, msg);
232 * Print out full_line with word wrap around def_loglinelen chars.
234 writeln_wrap(fp, full_line, len, def_loglinelen);
238 (void) lock_file(fileno(fp), SUDO_UNLOCK);
241 #ifdef HAVE_SETLOCALE
242 setlocale(LC_ALL, old_locale);
243 efree((void *)old_locale);
244 #endif /* HAVE_SETLOCALE */
250 * Log, audit and mail the denial message, optionally informing the user.
253 log_denial(int status, bool inform_user)
255 char *logline, *message;
256 debug_decl(log_denial, SUDO_DEBUG_LOGGING)
258 /* Handle auditing first. */
259 if (ISSET(status, FLAG_NO_USER | FLAG_NO_HOST))
260 audit_failure(NewArgv, _("No user or host"));
262 audit_failure(NewArgv, _("validation failure"));
264 /* Set error message. */
265 if (ISSET(status, FLAG_NO_USER))
266 message = _("user NOT in sudoers");
267 else if (ISSET(status, FLAG_NO_HOST))
268 message = _("user NOT authorized on host");
270 message = _("command not allowed");
272 logline = new_logline(message, 0);
274 if (should_mail(status))
275 send_mail("%s", logline); /* send mail based on status */
277 /* Inform the user if they failed to authenticate. */
279 if (ISSET(status, FLAG_NO_USER)) {
280 sudo_printf(SUDO_CONV_ERROR_MSG, _("%s is not in the sudoers "
281 "file. This incident will be reported.\n"), user_name);
282 } else if (ISSET(status, FLAG_NO_HOST)) {
283 sudo_printf(SUDO_CONV_ERROR_MSG, _("%s is not allowed to run sudo "
284 "on %s. This incident will be reported.\n"),
285 user_name, user_shost);
286 } else if (ISSET(status, FLAG_NO_CHECK)) {
287 sudo_printf(SUDO_CONV_ERROR_MSG, _("Sorry, user %s may not run "
288 "sudo on %s.\n"), user_name, user_shost);
290 sudo_printf(SUDO_CONV_ERROR_MSG, _("Sorry, user %s is not allowed "
291 "to execute '%s%s%s' as %s%s%s on %s.\n"),
292 user_name, user_cmnd, user_args ? " " : "",
293 user_args ? user_args : "",
294 list_pw ? list_pw->pw_name : runas_pw ?
295 runas_pw->pw_name : user_name, runas_gr ? ":" : "",
296 runas_gr ? runas_gr->gr_name : "", user_host);
301 * Log via syslog and/or a file.
304 do_syslog(def_syslog_badpri, logline);
313 * Log and audit that user was not allowed to run the command.
316 log_failure(int status, int flags)
318 debug_decl(log_failure, SUDO_DEBUG_LOGGING)
319 bool inform_user = true;
321 /* The user doesn't always get to see the log message (path info). */
322 if (!ISSET(status, FLAG_NO_USER | FLAG_NO_HOST) && def_path_info &&
323 (flags == NOT_FOUND_DOT || flags == NOT_FOUND))
325 log_denial(status, inform_user);
329 * We'd like to not leak path info at all here, but that can
330 * *really* confuse the users. To really close the leak we'd
331 * have to say "not allowed to run foo" even when the problem
332 * is just "no foo in path" since the user can trivially set
333 * their path to just contain a single dir.
335 if (flags == NOT_FOUND)
336 warningx(_("%s: command not found"), user_cmnd);
337 else if (flags == NOT_FOUND_DOT)
338 warningx(_("ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run."), user_cmnd, user_cmnd, user_cmnd);
345 * Log and audit that user was not able to authenticate themselves.
348 log_auth_failure(int status, int tries)
351 debug_decl(log_auth_failure, SUDO_DEBUG_LOGGING)
353 /* Handle auditing first. */
354 audit_failure(NewArgv, _("authentication failure"));
357 * Do we need to send mail?
358 * We want to avoid sending multiple messages for the same command
359 * so if we are going to send an email about the denial, that takes
362 if (ISSET(status, VALIDATE_OK)) {
363 /* Command allowed, auth failed; do we need to send mail? */
364 if (def_mail_badpass || def_mail_always)
367 /* Command denied, auth failed; make sure we don't send mail twice. */
368 if (def_mail_badpass && !should_mail(status))
370 /* Don't log the bad password message, we'll log a denial instead. */
375 * If sudoers denied the command we'll log that separately.
377 if (ISSET(status, FLAG_BAD_PASSWORD)) {
378 log_error(flags, ngettext("%d incorrect password attempt",
379 "%d incorrect password attempts", tries), tries);
380 } else if (ISSET(status, FLAG_NON_INTERACTIVE)) {
381 log_error(flags, _("a password is required"));
388 * Log and potentially mail the allowed command.
391 log_allowed(int status)
394 debug_decl(log_allowed, SUDO_DEBUG_LOGGING)
396 logline = new_logline(NULL, 0);
398 if (should_mail(status))
399 send_mail("%s", logline); /* send mail based on status */
402 * Log via syslog and/or a file.
405 do_syslog(def_syslog_goodpri, logline);
414 * Perform logging for log_error()/log_fatal()
417 vlog_error(int flags, const char *fmt, va_list ap)
420 char *logline, *message;
421 debug_decl(vlog_error, SUDO_DEBUG_LOGGING)
423 /* Expand printf-style format + args. */
424 evasprintf(&message, fmt, ap);
426 /* Become root if we are not already to avoid user interference */
427 set_perms(PERM_ROOT|PERM_NOEXIT);
429 if (ISSET(flags, MSG_ONLY))
432 logline = new_logline(message, ISSET(flags, USE_ERRNO) ? serrno : 0);
437 if (!ISSET(flags, NO_STDERR)) {
438 if (ISSET(flags, USE_ERRNO))
439 warning("%s", message);
441 warningx("%s", message);
443 if (logline != message)
447 * Send a copy of the error via mail.
449 if (!ISSET(flags, NO_MAIL))
450 send_mail("%s", logline);
453 * Log to syslog and/or a file.
455 if (!ISSET(flags, NO_LOG)) {
457 do_syslog(def_syslog_badpri, logline);
470 log_error(int flags, const char *fmt, ...)
473 debug_decl(log_error, SUDO_DEBUG_LOGGING)
477 vlog_error(flags, fmt, ap);
484 log_fatal(int flags, const char *fmt, ...)
487 debug_decl(log_error, SUDO_DEBUG_LOGGING)
491 vlog_error(flags, fmt, ap);
494 /* Exit the plugin. */
496 sudo_debug_exit(__func__, __FILE__, __LINE__, sudo_debug_subsys);
497 siglongjmp(error_jmp, 1);
500 #define MAX_MAILFLAGS 63
503 * Send a message to MAILTO user
506 send_mail(const char *fmt, ...)
510 int fd, pfd[2], status;
514 #ifndef NO_ROOT_MAILER
515 static char *root_envp[] = {
517 "PATH=/usr/bin:/bin:/usr/sbin:/sbin",
523 #endif /* NO_ROOT_MAILER */
524 debug_decl(send_mail, SUDO_DEBUG_LOGGING)
526 /* Just return if mailer is disabled. */
527 if (!def_mailerpath || !def_mailto)
530 /* Fork and return, child will daemonize. */
531 switch (pid = sudo_debug_fork()) {
534 error(1, _("unable to fork"));
538 switch (pid = fork()) {
541 mysyslog(LOG_ERR, _("unable to fork: %m"));
542 sudo_debug_printf(SUDO_DEBUG_ERROR, "unable to fork: %s",
546 /* Grandchild continues below. */
549 /* Parent will wait for us. */
556 rv = waitpid(pid, &status, 0);
557 } while (rv == -1 && errno == EINTR);
558 return; /* not debug */
561 /* Daemonize - disassociate from session/tty. */
564 if (chdir("/") == -1)
566 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0644)) != -1) {
567 (void) dup2(fd, STDIN_FILENO);
568 (void) dup2(fd, STDOUT_FILENO);
569 (void) dup2(fd, STDERR_FILENO);
572 #ifdef HAVE_SETLOCALE
573 if (!setlocale(LC_ALL, def_sudoers_locale)) {
574 setlocale(LC_ALL, "C");
575 efree(def_sudoers_locale);
576 def_sudoers_locale = estrdup("C");
578 #endif /* HAVE_SETLOCALE */
580 /* Close password, group and other fds so we don't leak. */
583 closefrom(STDERR_FILENO + 1);
585 /* Ignore SIGPIPE in case mailer exits prematurely (or is missing). */
586 zero_bytes(&sa, sizeof(sa));
587 sigemptyset(&sa.sa_mask);
588 sa.sa_flags = SA_INTERRUPT;
589 sa.sa_handler = SIG_IGN;
590 (void) sigaction(SIGPIPE, &sa, NULL);
592 if (pipe(pfd) == -1) {
593 mysyslog(LOG_ERR, _("unable to open pipe: %m"));
594 sudo_debug_printf(SUDO_DEBUG_ERROR, "unable to open pipe: %s",
596 sudo_debug_exit(__func__, __FILE__, __LINE__, sudo_debug_subsys);
600 switch (pid = sudo_debug_fork()) {
603 mysyslog(LOG_ERR, _("unable to fork: %m"));
604 sudo_debug_printf(SUDO_DEBUG_ERROR, "unable to fork: %s",
606 sudo_debug_exit(__func__, __FILE__, __LINE__, sudo_debug_subsys);
611 char *argv[MAX_MAILFLAGS + 1];
612 char *mpath, *mflags;
615 /* Child, set stdin to output side of the pipe */
616 if (pfd[0] != STDIN_FILENO) {
617 if (dup2(pfd[0], STDIN_FILENO) == -1) {
618 mysyslog(LOG_ERR, _("unable to dup stdin: %m"));
619 sudo_debug_printf(SUDO_DEBUG_ERROR,
620 "unable to dup stdin: %s", strerror(errno));
623 (void) close(pfd[0]);
625 (void) close(pfd[1]);
627 /* Build up an argv based on the mailer path and flags */
628 mflags = estrdup(def_mailerflags);
629 mpath = estrdup(def_mailerpath);
630 if ((argv[0] = strrchr(mpath, ' ')))
636 if ((p = strtok(mflags, " \t"))) {
639 } while (++i < MAX_MAILFLAGS && (p = strtok(NULL, " \t")));
644 * Depending on the config, either run the mailer as root
645 * (so user cannot kill it) or as the user (for the paranoid).
647 #ifndef NO_ROOT_MAILER
648 set_perms(PERM_ROOT|PERM_NOEXIT);
649 execve(mpath, argv, root_envp);
651 set_perms(PERM_FULL_USER|PERM_NOEXIT);
653 #endif /* NO_ROOT_MAILER */
654 mysyslog(LOG_ERR, _("unable to execute %s: %m"), mpath);
655 sudo_debug_printf(SUDO_DEBUG_ERROR, "unable to execute %s: %s",
656 mpath, strerror(errno));
662 (void) close(pfd[0]);
663 mail = fdopen(pfd[1], "w");
665 /* Pipes are all setup, send message. */
666 (void) fprintf(mail, "To: %s\nFrom: %s\nAuto-Submitted: %s\nSubject: ",
667 def_mailto, def_mailfrom ? def_mailfrom : user_name, "auto-generated");
668 for (p = def_mailsub; *p; p++) {
669 /* Expand escapes in the subject */
670 if (*p == '%' && *(p+1) != '%') {
673 (void) fputs(user_host, mail);
676 (void) fputs(user_name, mail);
683 (void) fputc(*p, mail);
686 #ifdef HAVE_NL_LANGINFO
687 if (strcmp(def_sudoers_locale, "C") != 0)
688 (void) fprintf(mail, "\nContent-Type: text/plain; charset=\"%s\"\nContent-Transfer-Encoding: 8bit", nl_langinfo(CODESET));
689 #endif /* HAVE_NL_LANGINFO */
691 (void) fprintf(mail, "\n\n%s : %s : %s : ", user_host,
692 get_timestr(time(NULL), def_log_year), user_name);
694 (void) vfprintf(mail, fmt, ap);
700 rv = waitpid(pid, &status, 0);
701 } while (rv == -1 && errno == EINTR);
702 sudo_debug_exit(__func__, __FILE__, __LINE__, sudo_debug_subsys);
707 * Determine whether we should send mail based on "status" and defaults options.
710 should_mail(int status)
712 debug_decl(should_mail, SUDO_DEBUG_LOGGING)
714 debug_return_bool(def_mail_always || ISSET(status, VALIDATE_ERROR) ||
715 (def_mail_no_user && ISSET(status, FLAG_NO_USER)) ||
716 (def_mail_no_host && ISSET(status, FLAG_NO_HOST)) ||
717 (def_mail_no_perms && !ISSET(status, VALIDATE_OK)));
720 #define LL_TTY_STR "TTY="
721 #define LL_CWD_STR "PWD=" /* XXX - should be CWD= */
722 #define LL_USER_STR "USER="
723 #define LL_GROUP_STR "GROUP="
724 #define LL_ENV_STR "ENV="
725 #define LL_CMND_STR "COMMAND="
726 #define LL_TSID_STR "TSID="
728 #define IS_SESSID(s) ( \
729 isalnum((unsigned char)(s)[0]) && isalnum((unsigned char)(s)[1]) && \
731 isalnum((unsigned char)(s)[3]) && isalnum((unsigned char)(s)[4]) && \
733 isalnum((unsigned char)(s)[6]) && isalnum((unsigned char)(s)[7]) && \
737 * Allocate and fill in a new logline.
740 new_logline(const char *message, int serrno)
745 char *line, sessid[7], *tsid = NULL;
746 debug_decl(new_logline, SUDO_DEBUG_LOGGING)
748 /* A TSID may be a sudoers-style session ID or a free-form string. */
749 if (sudo_user.iolog_file != NULL) {
750 if (IS_SESSID(sudo_user.iolog_file)) {
751 sessid[0] = sudo_user.iolog_file[0];
752 sessid[1] = sudo_user.iolog_file[1];
753 sessid[2] = sudo_user.iolog_file[3];
754 sessid[3] = sudo_user.iolog_file[4];
755 sessid[4] = sudo_user.iolog_file[6];
756 sessid[5] = sudo_user.iolog_file[7];
760 tsid = sudo_user.iolog_file;
765 * Compute line length
768 len += strlen(message) + 3;
770 errstr = strerror(serrno);
771 len += strlen(errstr) + 3;
773 len += sizeof(LL_TTY_STR) + 2 + strlen(user_tty);
774 len += sizeof(LL_CWD_STR) + 2 + strlen(user_cwd);
775 if (runas_pw != NULL)
776 len += sizeof(LL_USER_STR) + 2 + strlen(runas_pw->pw_name);
777 if (runas_gr != NULL)
778 len += sizeof(LL_GROUP_STR) + 2 + strlen(runas_gr->gr_name);
780 len += sizeof(LL_TSID_STR) + 2 + strlen(tsid);
781 if (sudo_user.env_vars != NULL) {
785 for (ep = sudo_user.env_vars; *ep != NULL; ep++)
786 evlen += strlen(*ep) + 1;
787 evstr = emalloc(evlen);
789 for (ep = sudo_user.env_vars; *ep != NULL; ep++) {
790 strlcat(evstr, *ep, evlen);
791 strlcat(evstr, " ", evlen); /* NOTE: last one will fail */
793 len += sizeof(LL_ENV_STR) + 2 + evlen;
795 if (user_cmnd != NULL) {
796 /* Note: we log "sudo -l command arg ..." as "list command arg ..." */
797 len += sizeof(LL_CMND_STR) - 1 + strlen(user_cmnd);
798 if (ISSET(sudo_mode, MODE_CHECK))
799 len += sizeof("list ") - 1;
800 if (user_args != NULL)
801 len += strlen(user_args) + 1;
805 * Allocate and build up the line.
807 line = emalloc(++len);
810 if (message != NULL) {
811 if (strlcat(line, message, len) >= len ||
812 strlcat(line, errstr ? " : " : " ; ", len) >= len)
816 if (strlcat(line, errstr, len) >= len ||
817 strlcat(line, " ; ", len) >= len)
820 if (strlcat(line, LL_TTY_STR, len) >= len ||
821 strlcat(line, user_tty, len) >= len ||
822 strlcat(line, " ; ", len) >= len)
824 if (strlcat(line, LL_CWD_STR, len) >= len ||
825 strlcat(line, user_cwd, len) >= len ||
826 strlcat(line, " ; ", len) >= len)
828 if (runas_pw != NULL) {
829 if (strlcat(line, LL_USER_STR, len) >= len ||
830 strlcat(line, runas_pw->pw_name, len) >= len ||
831 strlcat(line, " ; ", len) >= len)
834 if (runas_gr != NULL) {
835 if (strlcat(line, LL_GROUP_STR, len) >= len ||
836 strlcat(line, runas_gr->gr_name, len) >= len ||
837 strlcat(line, " ; ", len) >= len)
841 if (strlcat(line, LL_TSID_STR, len) >= len ||
842 strlcat(line, tsid, len) >= len ||
843 strlcat(line, " ; ", len) >= len)
847 if (strlcat(line, LL_ENV_STR, len) >= len ||
848 strlcat(line, evstr, len) >= len ||
849 strlcat(line, " ; ", len) >= len)
853 if (user_cmnd != NULL) {
854 if (strlcat(line, LL_CMND_STR, len) >= len)
856 if (ISSET(sudo_mode, MODE_CHECK) && strlcat(line, "list ", len) >= len)
858 if (strlcat(line, user_cmnd, len) >= len)
860 if (user_args != NULL) {
861 if (strlcat(line, " ", len) >= len ||
862 strlcat(line, user_args, len) >= len)
867 debug_return_str(line);
869 errorx(1, _("internal error: insufficient space for log line"));