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];
96 #ifdef LOG_NFACILITIES
97 openlog("sudo", 0, def_syslog);
101 vsnprintf(buf, sizeof(buf), fmt, ap);
104 * Some versions of syslog(3) don't guarantee success and return
105 * an int (notably HP-UX < 10.0). So, if at first we don't succeed,
108 for (i = 0; i < MAXSYSLOGTRIES; i++)
109 if (syslog(pri, "%s", buf) == 0)
112 syslog(pri, "%s", buf);
113 #endif /* BROKEN_SYSLOG */
118 #define FMT_FIRST "%8s : %s"
119 #define FMT_CONTD "%8s : (command continued) %s"
122 * Log a message to syslog, pre-pending the username and splitting the
123 * message into parts if it is longer than MAXSYSLOGLEN.
126 do_syslog(int pri, char *msg)
132 #ifdef HAVE_SETLOCALE
133 const char *old_locale = estrdup(setlocale(LC_ALL, NULL));
134 if (!setlocale(LC_ALL, def_sudoers_locale))
135 setlocale(LC_ALL, "C");
136 #endif /* HAVE_SETLOCALE */
139 * Log the full line, breaking into multiple syslog(3) calls if necessary
142 maxlen = MAXSYSLOGLEN - (strlen(fmt) - 5 + strlen(user_name));
143 for (p = msg; *p != '\0'; ) {
147 * Break up the line into what will fit on one syslog(3) line
148 * Try to avoid breaking words into several lines if possible.
150 tmp = memrchr(p, ' ', maxlen);
154 /* NULL terminate line, but save the char to restore later */
158 mysyslog(pri, fmt, user_name, p);
160 *tmp = save; /* restore saved character */
162 /* Advance p and eliminate leading whitespace */
163 for (p = tmp; *p == ' '; p++)
166 mysyslog(pri, fmt, user_name, p);
170 maxlen = MAXSYSLOGLEN - (strlen(fmt) - 5 + strlen(user_name));
173 #ifdef HAVE_SETLOCALE
174 setlocale(LC_ALL, old_locale);
175 efree((void *)old_locale);
176 #endif /* HAVE_SETLOCALE */
180 do_logfile(char *msg)
188 oldmask = umask(077);
189 fp = fopen(def_logfile, "a");
190 (void) umask(oldmask);
192 send_mail(_("unable to open log file: %s: %s"),
193 def_logfile, strerror(errno));
194 } else if (!lock_file(fileno(fp), SUDO_LOCK)) {
195 send_mail(_("unable to lock log file: %s: %s"),
196 def_logfile, strerror(errno));
198 #ifdef HAVE_SETLOCALE
199 const char *old_locale = estrdup(setlocale(LC_ALL, NULL));
200 if (!setlocale(LC_ALL, def_sudoers_locale))
201 setlocale(LC_ALL, "C");
202 #endif /* HAVE_SETLOCALE */
205 if (def_loglinelen < sizeof(LOG_INDENT)) {
206 /* Don't pretty-print long log file lines (hard to grep) */
208 (void) fprintf(fp, "%s : %s : HOST=%s : %s\n",
209 get_timestr(now, def_log_year), user_name, user_shost, msg);
211 (void) fprintf(fp, "%s : %s : %s\n",
212 get_timestr(now, def_log_year), user_name, msg);
215 len = easprintf(&full_line, "%s : %s : HOST=%s : %s",
216 get_timestr(now, def_log_year), user_name, user_shost, msg);
218 len = easprintf(&full_line, "%s : %s : %s",
219 get_timestr(now, def_log_year), user_name, msg);
222 * Print out full_line with word wrap around def_loglinelen chars.
224 writeln_wrap(fp, full_line, len, def_loglinelen);
228 (void) lock_file(fileno(fp), SUDO_UNLOCK);
231 #ifdef HAVE_SETLOCALE
232 setlocale(LC_ALL, old_locale);
233 efree((void *)old_locale);
234 #endif /* HAVE_SETLOCALE */
239 * Log and mail the denial message, optionally informing the user.
242 log_denial(int status, int inform_user)
247 /* Set error message. */
248 if (ISSET(status, FLAG_NO_USER))
249 message = _("user NOT in sudoers");
250 else if (ISSET(status, FLAG_NO_HOST))
251 message = _("user NOT authorized on host");
253 message = _("command not allowed");
255 logline = new_logline(message, 0);
257 if (should_mail(status))
258 send_mail("%s", logline); /* send mail based on status */
260 /* Inform the user if they failed to authenticate. */
262 if (ISSET(status, FLAG_NO_USER)) {
263 sudo_printf(SUDO_CONV_ERROR_MSG, _("%s is not in the sudoers "
264 "file. This incident will be reported.\n"), user_name);
265 } else if (ISSET(status, FLAG_NO_HOST)) {
266 sudo_printf(SUDO_CONV_ERROR_MSG, _("%s is not allowed to run sudo "
267 "on %s. This incident will be reported.\n"),
268 user_name, user_shost);
269 } else if (ISSET(status, FLAG_NO_CHECK)) {
270 sudo_printf(SUDO_CONV_ERROR_MSG, _("Sorry, user %s may not run "
271 "sudo on %s.\n"), user_name, user_shost);
273 sudo_printf(SUDO_CONV_ERROR_MSG, _("Sorry, user %s is not allowed "
274 "to execute '%s%s%s' as %s%s%s on %s.\n"),
275 user_name, user_cmnd, user_args ? " " : "",
276 user_args ? user_args : "",
277 list_pw ? list_pw->pw_name : runas_pw ?
278 runas_pw->pw_name : user_name, runas_gr ? ":" : "",
279 runas_gr ? runas_gr->gr_name : "", user_host);
284 * Log via syslog and/or a file.
287 do_syslog(def_syslog_badpri, logline);
295 * Log and potentially mail the allowed command.
298 log_allowed(int status)
302 logline = new_logline(NULL, 0);
304 if (should_mail(status))
305 send_mail("%s", logline); /* send mail based on status */
308 * Log via syslog and/or a file.
311 do_syslog(def_syslog_goodpri, logline);
319 log_error(int flags, const char *fmt, ...)
326 /* Expand printf-style format + args. */
328 evasprintf(&message, fmt, ap);
331 /* Become root if we are not already to avoid user interference */
332 set_perms(PERM_ROOT|PERM_NOEXIT);
334 if (ISSET(flags, MSG_ONLY))
337 logline = new_logline(message, ISSET(flags, USE_ERRNO) ? serrno : 0);
342 if (!ISSET(flags, NO_STDERR)) {
343 if (ISSET(flags, USE_ERRNO))
344 warning("%s", message);
346 warningx("%s", message);
348 if (logline != message)
352 * Send a copy of the error via mail.
354 if (!ISSET(flags, NO_MAIL))
355 send_mail("%s", logline);
358 * Log to syslog and/or a file.
361 do_syslog(def_syslog_badpri, logline);
369 if (!ISSET(flags, NO_EXIT)) {
371 siglongjmp(error_jmp, 1);
375 #define MAX_MAILFLAGS 63
378 * Send a message to MAILTO user
381 send_mail(const char *fmt, ...)
385 int fd, pfd[2], status;
389 #ifndef NO_ROOT_MAILER
390 static char *root_envp[] = {
392 "PATH=/usr/bin:/bin:/usr/sbin:/sbin",
398 #endif /* NO_ROOT_MAILER */
400 /* Just return if mailer is disabled. */
401 if (!def_mailerpath || !def_mailto)
404 /* Fork and return, child will daemonize. */
405 switch (pid = fork()) {
408 error(1, _("unable to fork"));
412 switch (pid = fork()) {
415 mysyslog(LOG_ERR, _("unable to fork: %m"));
418 /* Grandchild continues below. */
421 /* Parent will wait for us. */
428 rv = waitpid(pid, &status, 0);
429 } while (rv == -1 && errno == EINTR);
433 /* Daemonize - disassociate from session/tty. */
436 if (chdir("/") == -1)
438 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0644)) != -1) {
439 (void) dup2(fd, STDIN_FILENO);
440 (void) dup2(fd, STDOUT_FILENO);
441 (void) dup2(fd, STDERR_FILENO);
444 #ifdef HAVE_SETLOCALE
445 if (!setlocale(LC_ALL, def_sudoers_locale)) {
446 setlocale(LC_ALL, "C");
447 efree(def_sudoers_locale);
448 def_sudoers_locale = estrdup("C");
450 #endif /* HAVE_SETLOCALE */
452 /* Close password, group and other fds so we don't leak. */
455 closefrom(STDERR_FILENO + 1);
457 /* Ignore SIGPIPE in case mailer exits prematurely (or is missing). */
458 zero_bytes(&sa, sizeof(sa));
459 sigemptyset(&sa.sa_mask);
460 sa.sa_flags = SA_INTERRUPT;
461 sa.sa_handler = SIG_IGN;
462 (void) sigaction(SIGPIPE, &sa, NULL);
464 if (pipe(pfd) == -1) {
465 mysyslog(LOG_ERR, _("unable to open pipe: %m"));
469 switch (pid = fork()) {
472 mysyslog(LOG_ERR, _("unable to fork: %m"));
477 char *argv[MAX_MAILFLAGS + 1];
478 char *mpath, *mflags;
481 /* Child, set stdin to output side of the pipe */
482 if (pfd[0] != STDIN_FILENO) {
483 if (dup2(pfd[0], STDIN_FILENO) == -1) {
484 mysyslog(LOG_ERR, _("unable to dup stdin: %m"));
487 (void) close(pfd[0]);
489 (void) close(pfd[1]);
491 /* Build up an argv based on the mailer path and flags */
492 mflags = estrdup(def_mailerflags);
493 mpath = estrdup(def_mailerpath);
494 if ((argv[0] = strrchr(mpath, ' ')))
500 if ((p = strtok(mflags, " \t"))) {
503 } while (++i < MAX_MAILFLAGS && (p = strtok(NULL, " \t")));
508 * Depending on the config, either run the mailer as root
509 * (so user cannot kill it) or as the user (for the paranoid).
511 #ifndef NO_ROOT_MAILER
512 set_perms(PERM_ROOT|PERM_NOEXIT);
513 execve(mpath, argv, root_envp);
515 set_perms(PERM_FULL_USER|PERM_NOEXIT);
517 #endif /* NO_ROOT_MAILER */
518 mysyslog(LOG_ERR, _("unable to execute %s: %m"), mpath);
524 (void) close(pfd[0]);
525 mail = fdopen(pfd[1], "w");
527 /* Pipes are all setup, send message. */
528 (void) fprintf(mail, "To: %s\nFrom: %s\nAuto-Submitted: %s\nSubject: ",
529 def_mailto, def_mailfrom ? def_mailfrom : user_name, "auto-generated");
530 for (p = def_mailsub; *p; p++) {
531 /* Expand escapes in the subject */
532 if (*p == '%' && *(p+1) != '%') {
535 (void) fputs(user_host, mail);
538 (void) fputs(user_name, mail);
545 (void) fputc(*p, mail);
548 #ifdef HAVE_NL_LANGINFO
549 if (strcmp(def_sudoers_locale, "C") != 0)
550 (void) fprintf(mail, "\nContent-Type: text/plain; charset=\"%s\"\nContent-Transfer-Encoding: 8bit", nl_langinfo(CODESET));
551 #endif /* HAVE_NL_LANGINFO */
553 (void) fprintf(mail, "\n\n%s : %s : %s : ", user_host,
554 get_timestr(time(NULL), def_log_year), user_name);
556 (void) vfprintf(mail, fmt, ap);
562 rv = waitpid(pid, &status, 0);
563 } while (rv == -1 && errno == EINTR);
568 * Determine whether we should send mail based on "status" and defaults options.
571 should_mail(int status)
574 return def_mail_always || ISSET(status, VALIDATE_ERROR) ||
575 (def_mail_no_user && ISSET(status, FLAG_NO_USER)) ||
576 (def_mail_no_host && ISSET(status, FLAG_NO_HOST)) ||
577 (def_mail_no_perms && !ISSET(status, VALIDATE_OK));
580 #define LL_TTY_STR "TTY="
581 #define LL_CWD_STR "PWD=" /* XXX - should be CWD= */
582 #define LL_USER_STR "USER="
583 #define LL_GROUP_STR "GROUP="
584 #define LL_ENV_STR "ENV="
585 #define LL_CMND_STR "COMMAND="
586 #define LL_TSID_STR "TSID="
588 #define IS_SESSID(s) ( \
589 isalnum((unsigned char)(s)[0]) && isalnum((unsigned char)(s)[1]) && \
591 isalnum((unsigned char)(s)[3]) && isalnum((unsigned char)(s)[4]) && \
593 isalnum((unsigned char)(s)[6]) && isalnum((unsigned char)(s)[7]) && \
597 * Allocate and fill in a new logline.
600 new_logline(const char *message, int serrno)
605 char *line, sessid[7], *tsid = NULL;
607 /* A TSID may be a sudoers-style session ID or a free-form string. */
608 if (sudo_user.iolog_file != NULL) {
609 if (IS_SESSID(sudo_user.iolog_file)) {
610 sessid[0] = sudo_user.iolog_file[0];
611 sessid[1] = sudo_user.iolog_file[1];
612 sessid[2] = sudo_user.iolog_file[3];
613 sessid[3] = sudo_user.iolog_file[4];
614 sessid[4] = sudo_user.iolog_file[6];
615 sessid[5] = sudo_user.iolog_file[7];
619 tsid = sudo_user.iolog_file;
624 * Compute line length
627 len += strlen(message) + 3;
629 errstr = strerror(serrno);
630 len += strlen(errstr) + 3;
632 len += sizeof(LL_TTY_STR) + 2 + strlen(user_tty);
633 len += sizeof(LL_CWD_STR) + 2 + strlen(user_cwd);
634 if (runas_pw != NULL)
635 len += sizeof(LL_USER_STR) + 2 + strlen(runas_pw->pw_name);
636 if (runas_gr != NULL)
637 len += sizeof(LL_GROUP_STR) + 2 + strlen(runas_gr->gr_name);
639 len += sizeof(LL_TSID_STR) + 2 + strlen(tsid);
640 if (sudo_user.env_vars != NULL) {
644 for (ep = sudo_user.env_vars; *ep != NULL; ep++)
645 evlen += strlen(*ep) + 1;
646 evstr = emalloc(evlen);
648 for (ep = sudo_user.env_vars; *ep != NULL; ep++) {
649 strlcat(evstr, *ep, evlen);
650 strlcat(evstr, " ", evlen); /* NOTE: last one will fail */
652 len += sizeof(LL_ENV_STR) + 2 + evlen;
654 if (user_cmnd != NULL) {
655 /* Note: we log "sudo -l command arg ..." as "list command arg ..." */
656 len += sizeof(LL_CMND_STR) - 1 + strlen(user_cmnd);
657 if (ISSET(sudo_mode, MODE_CHECK))
658 len += sizeof("list ") - 1;
659 if (user_args != NULL)
660 len += strlen(user_args) + 1;
664 * Allocate and build up the line.
666 line = emalloc(++len);
669 if (message != NULL) {
670 if (strlcat(line, message, len) >= len ||
671 strlcat(line, errstr ? " : " : " ; ", len) >= len)
675 if (strlcat(line, errstr, len) >= len ||
676 strlcat(line, " ; ", len) >= len)
679 if (strlcat(line, LL_TTY_STR, len) >= len ||
680 strlcat(line, user_tty, len) >= len ||
681 strlcat(line, " ; ", len) >= len)
683 if (strlcat(line, LL_CWD_STR, len) >= len ||
684 strlcat(line, user_cwd, len) >= len ||
685 strlcat(line, " ; ", len) >= len)
687 if (runas_pw != NULL) {
688 if (strlcat(line, LL_USER_STR, len) >= len ||
689 strlcat(line, runas_pw->pw_name, len) >= len ||
690 strlcat(line, " ; ", len) >= len)
693 if (runas_gr != NULL) {
694 if (strlcat(line, LL_GROUP_STR, len) >= len ||
695 strlcat(line, runas_gr->gr_name, len) >= len ||
696 strlcat(line, " ; ", len) >= len)
700 if (strlcat(line, LL_TSID_STR, len) >= len ||
701 strlcat(line, tsid, len) >= len ||
702 strlcat(line, " ; ", len) >= len)
706 if (strlcat(line, LL_ENV_STR, len) >= len ||
707 strlcat(line, evstr, len) >= len ||
708 strlcat(line, " ; ", len) >= len)
712 if (user_cmnd != NULL) {
713 if (strlcat(line, LL_CMND_STR, len) >= len)
715 if (ISSET(sudo_mode, MODE_CHECK) && strlcat(line, "list ", len) >= len)
717 if (strlcat(line, user_cmnd, len) >= len)
719 if (user_args != NULL) {
720 if (strlcat(line, " ", len) >= len ||
721 strlcat(line, user_args, len) >= len)
728 errorx(1, _("internal error: insufficient space for log line"));