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 log_error(int flags, const char *fmt, ...)
332 char *logline, *message;
334 debug_decl(log_error, SUDO_DEBUG_LOGGING)
336 /* Expand printf-style format + args. */
338 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);
379 if (!ISSET(flags, NO_EXIT)) {
381 siglongjmp(error_jmp, 1);
386 #define MAX_MAILFLAGS 63
389 * Send a message to MAILTO user
392 send_mail(const char *fmt, ...)
396 int fd, pfd[2], status;
400 #ifndef NO_ROOT_MAILER
401 static char *root_envp[] = {
403 "PATH=/usr/bin:/bin:/usr/sbin:/sbin",
409 #endif /* NO_ROOT_MAILER */
410 debug_decl(send_mail, SUDO_DEBUG_LOGGING)
412 /* Just return if mailer is disabled. */
413 if (!def_mailerpath || !def_mailto)
416 /* Fork and return, child will daemonize. */
417 switch (pid = fork()) {
420 error(1, _("unable to fork"));
424 switch (pid = fork()) {
427 mysyslog(LOG_ERR, _("unable to fork: %m"));
428 sudo_debug_printf(SUDO_DEBUG_ERROR, "unable to fork: %s",
432 /* Grandchild continues below. */
435 /* Parent will wait for us. */
442 rv = waitpid(pid, &status, 0);
443 } while (rv == -1 && errno == EINTR);
444 return; /* not debug */
447 /* Daemonize - disassociate from session/tty. */
450 if (chdir("/") == -1)
452 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0644)) != -1) {
453 (void) dup2(fd, STDIN_FILENO);
454 (void) dup2(fd, STDOUT_FILENO);
455 (void) dup2(fd, STDERR_FILENO);
458 #ifdef HAVE_SETLOCALE
459 if (!setlocale(LC_ALL, def_sudoers_locale)) {
460 setlocale(LC_ALL, "C");
461 efree(def_sudoers_locale);
462 def_sudoers_locale = estrdup("C");
464 #endif /* HAVE_SETLOCALE */
466 /* Close password, group and other fds so we don't leak. */
469 closefrom(STDERR_FILENO + 1);
471 /* Ignore SIGPIPE in case mailer exits prematurely (or is missing). */
472 zero_bytes(&sa, sizeof(sa));
473 sigemptyset(&sa.sa_mask);
474 sa.sa_flags = SA_INTERRUPT;
475 sa.sa_handler = SIG_IGN;
476 (void) sigaction(SIGPIPE, &sa, NULL);
478 if (pipe(pfd) == -1) {
479 mysyslog(LOG_ERR, _("unable to open pipe: %m"));
480 sudo_debug_printf(SUDO_DEBUG_ERROR, "unable to open pipe: %s",
482 sudo_debug_exit(__func__, __FILE__, __LINE__, sudo_debug_subsys);
486 switch (pid = fork()) {
489 mysyslog(LOG_ERR, _("unable to fork: %m"));
490 sudo_debug_printf(SUDO_DEBUG_ERROR, "unable to fork: %s",
492 sudo_debug_exit(__func__, __FILE__, __LINE__, sudo_debug_subsys);
497 char *argv[MAX_MAILFLAGS + 1];
498 char *mpath, *mflags;
501 /* Child, set stdin to output side of the pipe */
502 if (pfd[0] != STDIN_FILENO) {
503 if (dup2(pfd[0], STDIN_FILENO) == -1) {
504 mysyslog(LOG_ERR, _("unable to dup stdin: %m"));
505 sudo_debug_printf(SUDO_DEBUG_ERROR,
506 "unable to dup stdin: %s", strerror(errno));
509 (void) close(pfd[0]);
511 (void) close(pfd[1]);
513 /* Build up an argv based on the mailer path and flags */
514 mflags = estrdup(def_mailerflags);
515 mpath = estrdup(def_mailerpath);
516 if ((argv[0] = strrchr(mpath, ' ')))
522 if ((p = strtok(mflags, " \t"))) {
525 } while (++i < MAX_MAILFLAGS && (p = strtok(NULL, " \t")));
530 * Depending on the config, either run the mailer as root
531 * (so user cannot kill it) or as the user (for the paranoid).
533 #ifndef NO_ROOT_MAILER
534 set_perms(PERM_ROOT|PERM_NOEXIT);
535 execve(mpath, argv, root_envp);
537 set_perms(PERM_FULL_USER|PERM_NOEXIT);
539 #endif /* NO_ROOT_MAILER */
540 mysyslog(LOG_ERR, _("unable to execute %s: %m"), mpath);
541 sudo_debug_printf(SUDO_DEBUG_ERROR, "unable to execute %s: %s",
542 mpath, strerror(errno));
548 (void) close(pfd[0]);
549 mail = fdopen(pfd[1], "w");
551 /* Pipes are all setup, send message. */
552 (void) fprintf(mail, "To: %s\nFrom: %s\nAuto-Submitted: %s\nSubject: ",
553 def_mailto, def_mailfrom ? def_mailfrom : user_name, "auto-generated");
554 for (p = def_mailsub; *p; p++) {
555 /* Expand escapes in the subject */
556 if (*p == '%' && *(p+1) != '%') {
559 (void) fputs(user_host, mail);
562 (void) fputs(user_name, mail);
569 (void) fputc(*p, mail);
572 #ifdef HAVE_NL_LANGINFO
573 if (strcmp(def_sudoers_locale, "C") != 0)
574 (void) fprintf(mail, "\nContent-Type: text/plain; charset=\"%s\"\nContent-Transfer-Encoding: 8bit", nl_langinfo(CODESET));
575 #endif /* HAVE_NL_LANGINFO */
577 (void) fprintf(mail, "\n\n%s : %s : %s : ", user_host,
578 get_timestr(time(NULL), def_log_year), user_name);
580 (void) vfprintf(mail, fmt, ap);
586 rv = waitpid(pid, &status, 0);
587 } while (rv == -1 && errno == EINTR);
588 sudo_debug_exit(__func__, __FILE__, __LINE__, sudo_debug_subsys);
593 * Determine whether we should send mail based on "status" and defaults options.
596 should_mail(int status)
598 debug_decl(should_mail, SUDO_DEBUG_LOGGING)
600 debug_return_bool(def_mail_always || ISSET(status, VALIDATE_ERROR) ||
601 (def_mail_no_user && ISSET(status, FLAG_NO_USER)) ||
602 (def_mail_no_host && ISSET(status, FLAG_NO_HOST)) ||
603 (def_mail_no_perms && !ISSET(status, VALIDATE_OK)));
606 #define LL_TTY_STR "TTY="
607 #define LL_CWD_STR "PWD=" /* XXX - should be CWD= */
608 #define LL_USER_STR "USER="
609 #define LL_GROUP_STR "GROUP="
610 #define LL_ENV_STR "ENV="
611 #define LL_CMND_STR "COMMAND="
612 #define LL_TSID_STR "TSID="
614 #define IS_SESSID(s) ( \
615 isalnum((unsigned char)(s)[0]) && isalnum((unsigned char)(s)[1]) && \
617 isalnum((unsigned char)(s)[3]) && isalnum((unsigned char)(s)[4]) && \
619 isalnum((unsigned char)(s)[6]) && isalnum((unsigned char)(s)[7]) && \
623 * Allocate and fill in a new logline.
626 new_logline(const char *message, int serrno)
631 char *line, sessid[7], *tsid = NULL;
632 debug_decl(new_logline, SUDO_DEBUG_LOGGING)
634 /* A TSID may be a sudoers-style session ID or a free-form string. */
635 if (sudo_user.iolog_file != NULL) {
636 if (IS_SESSID(sudo_user.iolog_file)) {
637 sessid[0] = sudo_user.iolog_file[0];
638 sessid[1] = sudo_user.iolog_file[1];
639 sessid[2] = sudo_user.iolog_file[3];
640 sessid[3] = sudo_user.iolog_file[4];
641 sessid[4] = sudo_user.iolog_file[6];
642 sessid[5] = sudo_user.iolog_file[7];
646 tsid = sudo_user.iolog_file;
651 * Compute line length
654 len += strlen(message) + 3;
656 errstr = strerror(serrno);
657 len += strlen(errstr) + 3;
659 len += sizeof(LL_TTY_STR) + 2 + strlen(user_tty);
660 len += sizeof(LL_CWD_STR) + 2 + strlen(user_cwd);
661 if (runas_pw != NULL)
662 len += sizeof(LL_USER_STR) + 2 + strlen(runas_pw->pw_name);
663 if (runas_gr != NULL)
664 len += sizeof(LL_GROUP_STR) + 2 + strlen(runas_gr->gr_name);
666 len += sizeof(LL_TSID_STR) + 2 + strlen(tsid);
667 if (sudo_user.env_vars != NULL) {
671 for (ep = sudo_user.env_vars; *ep != NULL; ep++)
672 evlen += strlen(*ep) + 1;
673 evstr = emalloc(evlen);
675 for (ep = sudo_user.env_vars; *ep != NULL; ep++) {
676 strlcat(evstr, *ep, evlen);
677 strlcat(evstr, " ", evlen); /* NOTE: last one will fail */
679 len += sizeof(LL_ENV_STR) + 2 + evlen;
681 if (user_cmnd != NULL) {
682 /* Note: we log "sudo -l command arg ..." as "list command arg ..." */
683 len += sizeof(LL_CMND_STR) - 1 + strlen(user_cmnd);
684 if (ISSET(sudo_mode, MODE_CHECK))
685 len += sizeof("list ") - 1;
686 if (user_args != NULL)
687 len += strlen(user_args) + 1;
691 * Allocate and build up the line.
693 line = emalloc(++len);
696 if (message != NULL) {
697 if (strlcat(line, message, len) >= len ||
698 strlcat(line, errstr ? " : " : " ; ", len) >= len)
702 if (strlcat(line, errstr, len) >= len ||
703 strlcat(line, " ; ", len) >= len)
706 if (strlcat(line, LL_TTY_STR, len) >= len ||
707 strlcat(line, user_tty, len) >= len ||
708 strlcat(line, " ; ", len) >= len)
710 if (strlcat(line, LL_CWD_STR, len) >= len ||
711 strlcat(line, user_cwd, len) >= len ||
712 strlcat(line, " ; ", len) >= len)
714 if (runas_pw != NULL) {
715 if (strlcat(line, LL_USER_STR, len) >= len ||
716 strlcat(line, runas_pw->pw_name, len) >= len ||
717 strlcat(line, " ; ", len) >= len)
720 if (runas_gr != NULL) {
721 if (strlcat(line, LL_GROUP_STR, len) >= len ||
722 strlcat(line, runas_gr->gr_name, len) >= len ||
723 strlcat(line, " ; ", len) >= len)
727 if (strlcat(line, LL_TSID_STR, len) >= len ||
728 strlcat(line, tsid, len) >= len ||
729 strlcat(line, " ; ", len) >= len)
733 if (strlcat(line, LL_ENV_STR, len) >= len ||
734 strlcat(line, evstr, len) >= len ||
735 strlcat(line, " ; ", len) >= len)
739 if (user_cmnd != NULL) {
740 if (strlcat(line, LL_CMND_STR, len) >= len)
742 if (ISSET(sudo_mode, MODE_CHECK) && strlcat(line, "list ", len) >= len)
744 if (strlcat(line, user_cmnd, len) >= len)
746 if (user_args != NULL) {
747 if (strlcat(line, " ", len) >= len ||
748 strlcat(line, user_args, len) >= len)
753 debug_return_str(line);
755 errorx(1, _("internal error: insufficient space for log line"));