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 #define MAXSYSLOGTRIES 16 /* num of retries for broken syslogs */
79 * We do an openlog(3)/closelog(3) for each message because some
80 * authentication methods (notably PAM) use syslog(3) for their
81 * own nefarious purposes and may call openlog(3) and closelog(3).
82 * Note that because we don't want to assume that all systems have
83 * vsyslog(3) (HP-UX doesn't) "%m" will not be expanded.
84 * Sadly this is a maze of #ifdefs.
87 mysyslog(int pri, const char *fmt, ...)
92 char buf[MAXSYSLOGLEN+1];
94 debug_decl(mysyslog, SUDO_DEBUG_LOGGING)
97 #ifdef LOG_NFACILITIES
98 openlog("sudo", 0, def_syslog);
102 vsnprintf(buf, sizeof(buf), fmt, ap);
105 * Some versions of syslog(3) don't guarantee success and return
106 * an int (notably HP-UX < 10.0). So, if at first we don't succeed,
109 for (i = 0; i < MAXSYSLOGTRIES; i++)
110 if (syslog(pri, "%s", buf) == 0)
113 syslog(pri, "%s", buf);
114 #endif /* BROKEN_SYSLOG */
120 #define FMT_FIRST "%8s : %s"
121 #define FMT_CONTD "%8s : (command continued) %s"
124 * Log a message to syslog, pre-pending the username and splitting the
125 * message into parts if it is longer than MAXSYSLOGLEN.
128 do_syslog(int pri, char *msg)
133 debug_decl(do_syslog, SUDO_DEBUG_LOGGING)
135 #ifdef HAVE_SETLOCALE
136 const char *old_locale = estrdup(setlocale(LC_ALL, NULL));
137 if (!setlocale(LC_ALL, def_sudoers_locale))
138 setlocale(LC_ALL, "C");
139 #endif /* HAVE_SETLOCALE */
142 * Log the full line, breaking into multiple syslog(3) calls if necessary
145 maxlen = MAXSYSLOGLEN - (strlen(fmt) - 5 + 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 - (strlen(fmt) - 5 + strlen(user_name));
176 #ifdef HAVE_SETLOCALE
177 setlocale(LC_ALL, old_locale);
178 efree((void *)old_locale);
179 #endif /* HAVE_SETLOCALE */
185 do_logfile(char *msg)
192 debug_decl(do_logfile, SUDO_DEBUG_LOGGING)
194 oldmask = umask(077);
195 fp = fopen(def_logfile, "a");
196 (void) umask(oldmask);
198 send_mail(_("unable to open log file: %s: %s"),
199 def_logfile, strerror(errno));
200 } else if (!lock_file(fileno(fp), SUDO_LOCK)) {
201 send_mail(_("unable to lock log file: %s: %s"),
202 def_logfile, strerror(errno));
204 #ifdef HAVE_SETLOCALE
205 const char *old_locale = estrdup(setlocale(LC_ALL, NULL));
206 if (!setlocale(LC_ALL, def_sudoers_locale))
207 setlocale(LC_ALL, "C");
208 #endif /* HAVE_SETLOCALE */
211 if (def_loglinelen < sizeof(LOG_INDENT)) {
212 /* Don't pretty-print long log file lines (hard to grep) */
214 (void) fprintf(fp, "%s : %s : HOST=%s : %s\n",
215 get_timestr(now, def_log_year), user_name, user_shost, msg);
217 (void) fprintf(fp, "%s : %s : %s\n",
218 get_timestr(now, def_log_year), user_name, msg);
221 len = easprintf(&full_line, "%s : %s : HOST=%s : %s",
222 get_timestr(now, def_log_year), user_name, user_shost, msg);
224 len = easprintf(&full_line, "%s : %s : %s",
225 get_timestr(now, def_log_year), user_name, msg);
228 * Print out full_line with word wrap around def_loglinelen chars.
230 writeln_wrap(fp, full_line, len, def_loglinelen);
234 (void) lock_file(fileno(fp), SUDO_UNLOCK);
237 #ifdef HAVE_SETLOCALE
238 setlocale(LC_ALL, old_locale);
239 efree((void *)old_locale);
240 #endif /* HAVE_SETLOCALE */
246 * Log and mail the denial message, optionally informing the user.
249 log_denial(int status, int inform_user)
251 char *logline, *message;
252 debug_decl(log_denial, SUDO_DEBUG_LOGGING)
254 /* Set error message. */
255 if (ISSET(status, FLAG_NO_USER))
256 message = _("user NOT in sudoers");
257 else if (ISSET(status, FLAG_NO_HOST))
258 message = _("user NOT authorized on host");
260 message = _("command not allowed");
262 logline = new_logline(message, 0);
264 if (should_mail(status))
265 send_mail("%s", logline); /* send mail based on status */
267 /* Inform the user if they failed to authenticate. */
269 if (ISSET(status, FLAG_NO_USER)) {
270 sudo_printf(SUDO_CONV_ERROR_MSG, _("%s is not in the sudoers "
271 "file. This incident will be reported.\n"), user_name);
272 } else if (ISSET(status, FLAG_NO_HOST)) {
273 sudo_printf(SUDO_CONV_ERROR_MSG, _("%s is not allowed to run sudo "
274 "on %s. This incident will be reported.\n"),
275 user_name, user_shost);
276 } else if (ISSET(status, FLAG_NO_CHECK)) {
277 sudo_printf(SUDO_CONV_ERROR_MSG, _("Sorry, user %s may not run "
278 "sudo on %s.\n"), user_name, user_shost);
280 sudo_printf(SUDO_CONV_ERROR_MSG, _("Sorry, user %s is not allowed "
281 "to execute '%s%s%s' as %s%s%s on %s.\n"),
282 user_name, user_cmnd, user_args ? " " : "",
283 user_args ? user_args : "",
284 list_pw ? list_pw->pw_name : runas_pw ?
285 runas_pw->pw_name : user_name, runas_gr ? ":" : "",
286 runas_gr ? runas_gr->gr_name : "", user_host);
291 * Log via syslog and/or a file.
294 do_syslog(def_syslog_badpri, logline);
303 * Log and potentially mail the allowed command.
306 log_allowed(int status)
309 debug_decl(log_allowed, SUDO_DEBUG_LOGGING)
311 logline = new_logline(NULL, 0);
313 if (should_mail(status))
314 send_mail("%s", logline); /* send mail based on status */
317 * Log via syslog and/or a file.
320 do_syslog(def_syslog_goodpri, logline);
329 * Perform logging for log_error()/log_fatal()
332 vlog_error(int flags, const char *fmt, va_list ap)
335 char *logline, *message;
336 debug_decl(vlog_error, SUDO_DEBUG_LOGGING)
338 /* Expand printf-style format + args. */
339 evasprintf(&message, fmt, ap);
341 /* Become root if we are not already to avoid user interference */
342 set_perms(PERM_ROOT|PERM_NOEXIT);
344 if (ISSET(flags, MSG_ONLY))
347 logline = new_logline(message, ISSET(flags, USE_ERRNO) ? serrno : 0);
352 if (!ISSET(flags, NO_STDERR)) {
353 if (ISSET(flags, USE_ERRNO))
354 warning("%s", message);
356 warningx("%s", message);
358 if (logline != message)
362 * Send a copy of the error via mail.
364 if (!ISSET(flags, NO_MAIL))
365 send_mail("%s", logline);
368 * Log to syslog and/or a file.
371 do_syslog(def_syslog_badpri, logline);
383 log_error(int flags, const char *fmt, ...)
386 debug_decl(log_error, SUDO_DEBUG_LOGGING)
390 vlog_error(flags, fmt, ap);
397 log_fatal(int flags, const char *fmt, ...)
400 debug_decl(log_error, SUDO_DEBUG_LOGGING)
404 vlog_error(flags, fmt, ap);
407 /* Exit the plugin. */
409 sudo_debug_exit(__func__, __FILE__, __LINE__, sudo_debug_subsys);
410 siglongjmp(error_jmp, 1);
413 #define MAX_MAILFLAGS 63
416 * Send a message to MAILTO user
419 send_mail(const char *fmt, ...)
423 int fd, pfd[2], status;
427 #ifndef NO_ROOT_MAILER
428 static char *root_envp[] = {
430 "PATH=/usr/bin:/bin:/usr/sbin:/sbin",
436 #endif /* NO_ROOT_MAILER */
437 debug_decl(send_mail, SUDO_DEBUG_LOGGING)
439 /* Just return if mailer is disabled. */
440 if (!def_mailerpath || !def_mailto)
443 /* Fork and return, child will daemonize. */
444 switch (pid = sudo_debug_fork()) {
447 error(1, _("unable to fork"));
451 switch (pid = fork()) {
454 mysyslog(LOG_ERR, _("unable to fork: %m"));
455 sudo_debug_printf(SUDO_DEBUG_ERROR, "unable to fork: %s",
459 /* Grandchild continues below. */
462 /* Parent will wait for us. */
469 rv = waitpid(pid, &status, 0);
470 } while (rv == -1 && errno == EINTR);
471 return; /* not debug */
474 /* Daemonize - disassociate from session/tty. */
477 if (chdir("/") == -1)
479 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0644)) != -1) {
480 (void) dup2(fd, STDIN_FILENO);
481 (void) dup2(fd, STDOUT_FILENO);
482 (void) dup2(fd, STDERR_FILENO);
485 #ifdef HAVE_SETLOCALE
486 if (!setlocale(LC_ALL, def_sudoers_locale)) {
487 setlocale(LC_ALL, "C");
488 efree(def_sudoers_locale);
489 def_sudoers_locale = estrdup("C");
491 #endif /* HAVE_SETLOCALE */
493 /* Close password, group and other fds so we don't leak. */
496 closefrom(STDERR_FILENO + 1);
498 /* Ignore SIGPIPE in case mailer exits prematurely (or is missing). */
499 zero_bytes(&sa, sizeof(sa));
500 sigemptyset(&sa.sa_mask);
501 sa.sa_flags = SA_INTERRUPT;
502 sa.sa_handler = SIG_IGN;
503 (void) sigaction(SIGPIPE, &sa, NULL);
505 if (pipe(pfd) == -1) {
506 mysyslog(LOG_ERR, _("unable to open pipe: %m"));
507 sudo_debug_printf(SUDO_DEBUG_ERROR, "unable to open pipe: %s",
509 sudo_debug_exit(__func__, __FILE__, __LINE__, sudo_debug_subsys);
513 switch (pid = sudo_debug_fork()) {
516 mysyslog(LOG_ERR, _("unable to fork: %m"));
517 sudo_debug_printf(SUDO_DEBUG_ERROR, "unable to fork: %s",
519 sudo_debug_exit(__func__, __FILE__, __LINE__, sudo_debug_subsys);
524 char *argv[MAX_MAILFLAGS + 1];
525 char *mpath, *mflags;
528 /* Child, set stdin to output side of the pipe */
529 if (pfd[0] != STDIN_FILENO) {
530 if (dup2(pfd[0], STDIN_FILENO) == -1) {
531 mysyslog(LOG_ERR, _("unable to dup stdin: %m"));
532 sudo_debug_printf(SUDO_DEBUG_ERROR,
533 "unable to dup stdin: %s", strerror(errno));
536 (void) close(pfd[0]);
538 (void) close(pfd[1]);
540 /* Build up an argv based on the mailer path and flags */
541 mflags = estrdup(def_mailerflags);
542 mpath = estrdup(def_mailerpath);
543 if ((argv[0] = strrchr(mpath, ' ')))
549 if ((p = strtok(mflags, " \t"))) {
552 } while (++i < MAX_MAILFLAGS && (p = strtok(NULL, " \t")));
557 * Depending on the config, either run the mailer as root
558 * (so user cannot kill it) or as the user (for the paranoid).
560 #ifndef NO_ROOT_MAILER
561 set_perms(PERM_ROOT|PERM_NOEXIT);
562 execve(mpath, argv, root_envp);
564 set_perms(PERM_FULL_USER|PERM_NOEXIT);
566 #endif /* NO_ROOT_MAILER */
567 mysyslog(LOG_ERR, _("unable to execute %s: %m"), mpath);
568 sudo_debug_printf(SUDO_DEBUG_ERROR, "unable to execute %s: %s",
569 mpath, strerror(errno));
575 (void) close(pfd[0]);
576 mail = fdopen(pfd[1], "w");
578 /* Pipes are all setup, send message. */
579 (void) fprintf(mail, "To: %s\nFrom: %s\nAuto-Submitted: %s\nSubject: ",
580 def_mailto, def_mailfrom ? def_mailfrom : user_name, "auto-generated");
581 for (p = def_mailsub; *p; p++) {
582 /* Expand escapes in the subject */
583 if (*p == '%' && *(p+1) != '%') {
586 (void) fputs(user_host, mail);
589 (void) fputs(user_name, mail);
596 (void) fputc(*p, mail);
599 #ifdef HAVE_NL_LANGINFO
600 if (strcmp(def_sudoers_locale, "C") != 0)
601 (void) fprintf(mail, "\nContent-Type: text/plain; charset=\"%s\"\nContent-Transfer-Encoding: 8bit", nl_langinfo(CODESET));
602 #endif /* HAVE_NL_LANGINFO */
604 (void) fprintf(mail, "\n\n%s : %s : %s : ", user_host,
605 get_timestr(time(NULL), def_log_year), user_name);
607 (void) vfprintf(mail, fmt, ap);
613 rv = waitpid(pid, &status, 0);
614 } while (rv == -1 && errno == EINTR);
615 sudo_debug_exit(__func__, __FILE__, __LINE__, sudo_debug_subsys);
620 * Determine whether we should send mail based on "status" and defaults options.
623 should_mail(int status)
625 debug_decl(should_mail, SUDO_DEBUG_LOGGING)
627 debug_return_bool(def_mail_always || ISSET(status, VALIDATE_ERROR) ||
628 (def_mail_no_user && ISSET(status, FLAG_NO_USER)) ||
629 (def_mail_no_host && ISSET(status, FLAG_NO_HOST)) ||
630 (def_mail_no_perms && !ISSET(status, VALIDATE_OK)));
633 #define LL_TTY_STR "TTY="
634 #define LL_CWD_STR "PWD=" /* XXX - should be CWD= */
635 #define LL_USER_STR "USER="
636 #define LL_GROUP_STR "GROUP="
637 #define LL_ENV_STR "ENV="
638 #define LL_CMND_STR "COMMAND="
639 #define LL_TSID_STR "TSID="
641 #define IS_SESSID(s) ( \
642 isalnum((unsigned char)(s)[0]) && isalnum((unsigned char)(s)[1]) && \
644 isalnum((unsigned char)(s)[3]) && isalnum((unsigned char)(s)[4]) && \
646 isalnum((unsigned char)(s)[6]) && isalnum((unsigned char)(s)[7]) && \
650 * Allocate and fill in a new logline.
653 new_logline(const char *message, int serrno)
658 char *line, sessid[7], *tsid = NULL;
659 debug_decl(new_logline, SUDO_DEBUG_LOGGING)
661 /* A TSID may be a sudoers-style session ID or a free-form string. */
662 if (sudo_user.iolog_file != NULL) {
663 if (IS_SESSID(sudo_user.iolog_file)) {
664 sessid[0] = sudo_user.iolog_file[0];
665 sessid[1] = sudo_user.iolog_file[1];
666 sessid[2] = sudo_user.iolog_file[3];
667 sessid[3] = sudo_user.iolog_file[4];
668 sessid[4] = sudo_user.iolog_file[6];
669 sessid[5] = sudo_user.iolog_file[7];
673 tsid = sudo_user.iolog_file;
678 * Compute line length
681 len += strlen(message) + 3;
683 errstr = strerror(serrno);
684 len += strlen(errstr) + 3;
686 len += sizeof(LL_TTY_STR) + 2 + strlen(user_tty);
687 len += sizeof(LL_CWD_STR) + 2 + strlen(user_cwd);
688 if (runas_pw != NULL)
689 len += sizeof(LL_USER_STR) + 2 + strlen(runas_pw->pw_name);
690 if (runas_gr != NULL)
691 len += sizeof(LL_GROUP_STR) + 2 + strlen(runas_gr->gr_name);
693 len += sizeof(LL_TSID_STR) + 2 + strlen(tsid);
694 if (sudo_user.env_vars != NULL) {
698 for (ep = sudo_user.env_vars; *ep != NULL; ep++)
699 evlen += strlen(*ep) + 1;
700 evstr = emalloc(evlen);
702 for (ep = sudo_user.env_vars; *ep != NULL; ep++) {
703 strlcat(evstr, *ep, evlen);
704 strlcat(evstr, " ", evlen); /* NOTE: last one will fail */
706 len += sizeof(LL_ENV_STR) + 2 + evlen;
708 if (user_cmnd != NULL) {
709 /* Note: we log "sudo -l command arg ..." as "list command arg ..." */
710 len += sizeof(LL_CMND_STR) - 1 + strlen(user_cmnd);
711 if (ISSET(sudo_mode, MODE_CHECK))
712 len += sizeof("list ") - 1;
713 if (user_args != NULL)
714 len += strlen(user_args) + 1;
718 * Allocate and build up the line.
720 line = emalloc(++len);
723 if (message != NULL) {
724 if (strlcat(line, message, len) >= len ||
725 strlcat(line, errstr ? " : " : " ; ", len) >= len)
729 if (strlcat(line, errstr, len) >= len ||
730 strlcat(line, " ; ", len) >= len)
733 if (strlcat(line, LL_TTY_STR, len) >= len ||
734 strlcat(line, user_tty, len) >= len ||
735 strlcat(line, " ; ", len) >= len)
737 if (strlcat(line, LL_CWD_STR, len) >= len ||
738 strlcat(line, user_cwd, len) >= len ||
739 strlcat(line, " ; ", len) >= len)
741 if (runas_pw != NULL) {
742 if (strlcat(line, LL_USER_STR, len) >= len ||
743 strlcat(line, runas_pw->pw_name, len) >= len ||
744 strlcat(line, " ; ", len) >= len)
747 if (runas_gr != NULL) {
748 if (strlcat(line, LL_GROUP_STR, len) >= len ||
749 strlcat(line, runas_gr->gr_name, len) >= len ||
750 strlcat(line, " ; ", len) >= len)
754 if (strlcat(line, LL_TSID_STR, len) >= len ||
755 strlcat(line, tsid, len) >= len ||
756 strlcat(line, " ; ", len) >= len)
760 if (strlcat(line, LL_ENV_STR, len) >= len ||
761 strlcat(line, evstr, len) >= len ||
762 strlcat(line, " ; ", len) >= len)
766 if (user_cmnd != NULL) {
767 if (strlcat(line, LL_CMND_STR, len) >= len)
769 if (ISSET(sudo_mode, MODE_CHECK) && strlcat(line, "list ", len) >= len)
771 if (strlcat(line, user_cmnd, len) >= len)
773 if (user_args != NULL) {
774 if (strlcat(line, " ", len) >= len ||
775 strlcat(line, user_args, len) >= len)
780 debug_return_str(line);
782 errorx(1, _("internal error: insufficient space for log line"));