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 - (sizeof(FMT_FIRST) - 6 + 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 - (sizeof(FMT_CONTD) - 6 + 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)
183 char *beg, *oldend, *end;
188 oldmask = umask(077);
189 maxlen = def_loglinelen > 0 ? def_loglinelen : 0;
190 fp = fopen(def_logfile, "a");
191 (void) umask(oldmask);
193 send_mail("Can't open log file: %s: %s", def_logfile, strerror(errno));
194 } else if (!lock_file(fileno(fp), SUDO_LOCK)) {
195 send_mail("Can't lock log file: %s: %s", def_logfile, strerror(errno));
199 #ifdef HAVE_SETLOCALE
200 const char *old_locale = estrdup(setlocale(LC_ALL, NULL));
201 if (!setlocale(LC_ALL, def_sudoers_locale))
202 setlocale(LC_ALL, "C");
203 #endif /* HAVE_SETLOCALE */
206 if (def_loglinelen == 0) {
207 /* Don't pretty-print long log file lines (hard to grep) */
209 (void) fprintf(fp, "%s : %s : HOST=%s : %s\n",
210 get_timestr(now, def_log_year), user_name, user_shost, msg);
212 (void) fprintf(fp, "%s : %s : %s\n",
213 get_timestr(now, def_log_year), user_name, msg);
216 easprintf(&full_line, "%s : %s : HOST=%s : %s",
217 get_timestr(now, def_log_year), user_name, user_shost, msg);
219 easprintf(&full_line, "%s : %s : %s",
220 get_timestr(now, def_log_year), user_name, msg);
223 * Print out full_line with word wrap
225 beg = end = full_line;
228 end = strchr(oldend, ' ');
230 if (maxlen > 0 && end) {
232 if (strlen(beg) > maxlen) {
233 /* too far, need to back up & print the line */
235 if (beg == (char *)full_line)
236 maxlen -= 4; /* don't indent first line */
245 (void) fprintf(fp, "%s\n ", beg);
248 (void) fprintf(fp, "%s\n ", beg);
251 /* reset beg to point to the start of the new substr */
256 /* we still have room */
260 /* remove leading whitespace */
265 (void) fprintf(fp, "%s\n", beg);
266 beg = NULL; /* exit condition */
272 (void) lock_file(fileno(fp), SUDO_UNLOCK);
275 #ifdef HAVE_SETLOCALE
276 setlocale(LC_ALL, old_locale);
277 efree((void *)old_locale);
278 #endif /* HAVE_SETLOCALE */
283 * Log and mail the denial message, optionally informing the user.
286 log_denial(int status, int inform_user)
291 /* Set error message. */
292 if (ISSET(status, FLAG_NO_USER))
293 message = "user NOT in sudoers";
294 else if (ISSET(status, FLAG_NO_HOST))
295 message = "user NOT authorized on host";
297 message = "command not allowed";
299 logline = new_logline(message, 0);
301 if (should_mail(status))
302 send_mail("%s", logline); /* send mail based on status */
304 /* Inform the user if they failed to authenticate. */
306 if (ISSET(status, FLAG_NO_USER)) {
307 sudo_printf(SUDO_CONV_ERROR_MSG, "%s is not in the sudoers file. "
308 "This incident will be reported.\n", user_name);
309 } else if (ISSET(status, FLAG_NO_HOST)) {
310 sudo_printf(SUDO_CONV_ERROR_MSG, "%s is not allowed to run sudo "
311 "on %s. This incident will be reported.\n",
312 user_name, user_shost);
313 } else if (ISSET(status, FLAG_NO_CHECK)) {
314 sudo_printf(SUDO_CONV_ERROR_MSG, "Sorry, user %s may not run "
315 "sudo on %s.\n", user_name, user_shost);
317 sudo_printf(SUDO_CONV_ERROR_MSG, "Sorry, user %s is not allowed "
318 "to execute '%s%s%s' as %s%s%s on %s.\n",
319 user_name, user_cmnd, user_args ? " " : "",
320 user_args ? user_args : "",
321 list_pw ? list_pw->pw_name : runas_pw ?
322 runas_pw->pw_name : user_name, runas_gr ? ":" : "",
323 runas_gr ? runas_gr->gr_name : "", user_host);
328 * Log via syslog and/or a file.
331 do_syslog(def_syslog_badpri, logline);
339 * Log and potentially mail the allowed command.
342 log_allowed(int status)
346 logline = new_logline(NULL, 0);
348 if (should_mail(status))
349 send_mail("%s", logline); /* send mail based on status */
352 * Log via syslog and/or a file.
355 do_syslog(def_syslog_goodpri, logline);
363 log_error(int flags, const char *fmt, ...)
370 /* Expand printf-style format + args. */
372 evasprintf(&message, fmt, ap);
375 /* Become root if we are not already to avoid user interference */
376 set_perms(PERM_ROOT|PERM_NOEXIT);
378 if (ISSET(flags, MSG_ONLY))
381 logline = new_logline(message, ISSET(flags, USE_ERRNO) ? serrno : 0);
386 if (!ISSET(flags, NO_STDERR)) {
387 if (ISSET(flags, USE_ERRNO))
388 warning("%s", message);
390 warningx("%s", message);
392 if (logline != message)
396 * Send a copy of the error via mail.
398 if (!ISSET(flags, NO_MAIL))
399 send_mail("%s", logline);
402 * Log to syslog and/or a file.
405 do_syslog(def_syslog_badpri, logline);
413 if (!ISSET(flags, NO_EXIT)) {
415 siglongjmp(error_jmp, 1);
419 #define MAX_MAILFLAGS 63
422 * Send a message to MAILTO user
425 send_mail(const char *fmt, ...)
429 int fd, pfd[2], status;
433 #ifndef NO_ROOT_MAILER
434 static char *root_envp[] = {
436 "PATH=/usr/bin:/bin:/usr/sbin:/sbin",
442 #endif /* NO_ROOT_MAILER */
444 /* Just return if mailer is disabled. */
445 if (!def_mailerpath || !def_mailto)
448 /* Fork and return, child will daemonize. */
449 switch (pid = fork()) {
452 error(1, "cannot fork");
456 switch (pid = fork()) {
459 mysyslog(LOG_ERR, "cannot fork: %m");
462 /* Grandchild continues below. */
465 /* Parent will wait for us. */
472 rv = waitpid(pid, &status, 0);
473 } while (rv == -1 && errno == EINTR);
477 /* Daemonize - disassociate from session/tty. */
480 if (chdir("/") == -1)
482 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0644)) != -1) {
483 (void) dup2(fd, STDIN_FILENO);
484 (void) dup2(fd, STDOUT_FILENO);
485 (void) dup2(fd, STDERR_FILENO);
488 #ifdef HAVE_SETLOCALE
489 if (!setlocale(LC_ALL, def_sudoers_locale)) {
490 setlocale(LC_ALL, "C");
491 efree(def_sudoers_locale);
492 def_sudoers_locale = estrdup("C");
494 #endif /* HAVE_SETLOCALE */
496 /* Close password, group and other fds so we don't leak. */
499 closefrom(STDERR_FILENO + 1);
501 /* Ignore SIGPIPE in case mailer exits prematurely (or is missing). */
502 zero_bytes(&sa, sizeof(sa));
503 sigemptyset(&sa.sa_mask);
504 sa.sa_flags = SA_INTERRUPT;
505 sa.sa_handler = SIG_IGN;
506 (void) sigaction(SIGPIPE, &sa, NULL);
508 if (pipe(pfd) == -1) {
509 mysyslog(LOG_ERR, "cannot open pipe: %m");
513 switch (pid = fork()) {
516 mysyslog(LOG_ERR, "cannot fork: %m");
521 char *argv[MAX_MAILFLAGS + 1];
522 char *mpath, *mflags;
525 /* Child, set stdin to output side of the pipe */
526 if (pfd[0] != STDIN_FILENO) {
527 if (dup2(pfd[0], STDIN_FILENO) == -1) {
528 mysyslog(LOG_ERR, "cannot dup stdin: %m");
531 (void) close(pfd[0]);
533 (void) close(pfd[1]);
535 /* Build up an argv based on the mailer path and flags */
536 mflags = estrdup(def_mailerflags);
537 mpath = estrdup(def_mailerpath);
538 if ((argv[0] = strrchr(mpath, ' ')))
544 if ((p = strtok(mflags, " \t"))) {
547 } while (++i < MAX_MAILFLAGS && (p = strtok(NULL, " \t")));
552 * Depending on the config, either run the mailer as root
553 * (so user cannot kill it) or as the user (for the paranoid).
555 #ifndef NO_ROOT_MAILER
556 set_perms(PERM_ROOT|PERM_NOEXIT);
557 execve(mpath, argv, root_envp);
559 set_perms(PERM_FULL_USER|PERM_NOEXIT);
561 #endif /* NO_ROOT_MAILER */
562 mysyslog(LOG_ERR, "cannot execute %s: %m", mpath);
568 (void) close(pfd[0]);
569 mail = fdopen(pfd[1], "w");
571 /* Pipes are all setup, send message. */
572 (void) fprintf(mail, "To: %s\nFrom: %s\nAuto-Submitted: %s\nSubject: ",
573 def_mailto, def_mailfrom ? def_mailfrom : user_name, "auto-generated");
574 for (p = def_mailsub; *p; p++) {
575 /* Expand escapes in the subject */
576 if (*p == '%' && *(p+1) != '%') {
579 (void) fputs(user_host, mail);
582 (void) fputs(user_name, mail);
589 (void) fputc(*p, mail);
592 #ifdef HAVE_NL_LANGINFO
593 if (strcmp(def_sudoers_locale, "C") != 0)
594 (void) fprintf(mail, "\nContent-Type: text/plain; charset=\"%s\"\nContent-Transfer-Encoding: 8bit", nl_langinfo(CODESET));
595 #endif /* HAVE_NL_LANGINFO */
597 (void) fprintf(mail, "\n\n%s : %s : %s : ", user_host,
598 get_timestr(time(NULL), def_log_year), user_name);
600 (void) vfprintf(mail, fmt, ap);
606 rv = waitpid(pid, &status, 0);
607 } while (rv == -1 && errno == EINTR);
612 * Determine whether we should send mail based on "status" and defaults options.
615 should_mail(int status)
618 return def_mail_always || ISSET(status, VALIDATE_ERROR) ||
619 (def_mail_no_user && ISSET(status, FLAG_NO_USER)) ||
620 (def_mail_no_host && ISSET(status, FLAG_NO_HOST)) ||
621 (def_mail_no_perms && !ISSET(status, VALIDATE_OK));
624 #define LL_TTY_STR "TTY="
625 #define LL_CWD_STR "PWD=" /* XXX - should be CWD= */
626 #define LL_USER_STR "USER="
627 #define LL_GROUP_STR "GROUP="
628 #define LL_ENV_STR "ENV="
629 #define LL_CMND_STR "COMMAND="
630 #define LL_TSID_STR "TSID="
632 #define IS_SESSID(s) ( \
633 isalnum((unsigned char)(s)[0]) && isalnum((unsigned char)(s)[1]) && \
635 isalnum((unsigned char)(s)[3]) && isalnum((unsigned char)(s)[4]) && \
637 isalnum((unsigned char)(s)[6]) && isalnum((unsigned char)(s)[7]) && \
641 * Allocate and fill in a new logline.
644 new_logline(const char *message, int serrno)
649 char *line, sessid[7], *tsid = NULL;
651 /* A TSID may be a sudoers-style session ID or a free-form string. */
652 if (sudo_user.iolog_file != NULL) {
653 if (IS_SESSID(sudo_user.iolog_file)) {
654 sessid[0] = sudo_user.iolog_file[0];
655 sessid[1] = sudo_user.iolog_file[1];
656 sessid[2] = sudo_user.iolog_file[3];
657 sessid[3] = sudo_user.iolog_file[4];
658 sessid[4] = sudo_user.iolog_file[6];
659 sessid[5] = sudo_user.iolog_file[7];
663 tsid = sudo_user.iolog_file;
668 * Compute line length
671 len += strlen(message) + 3;
673 errstr = strerror(serrno);
674 len += strlen(errstr) + 3;
676 len += sizeof(LL_TTY_STR) + 2 + strlen(user_tty);
677 len += sizeof(LL_CWD_STR) + 2 + strlen(user_cwd);
678 if (runas_pw != NULL)
679 len += sizeof(LL_USER_STR) + 2 + strlen(runas_pw->pw_name);
680 if (runas_gr != NULL)
681 len += sizeof(LL_GROUP_STR) + 2 + strlen(runas_gr->gr_name);
683 len += sizeof(LL_TSID_STR) + 2 + strlen(tsid);
684 if (sudo_user.env_vars != NULL) {
688 for (ep = sudo_user.env_vars; *ep != NULL; ep++)
689 evlen += strlen(*ep) + 1;
690 evstr = emalloc(evlen);
692 for (ep = sudo_user.env_vars; *ep != NULL; ep++) {
693 strlcat(evstr, *ep, evlen);
694 strlcat(evstr, " ", evlen); /* NOTE: last one will fail */
696 len += sizeof(LL_ENV_STR) + 2 + evlen;
698 if (user_cmnd != NULL) {
699 /* Note: we log "sudo -l command arg ..." as "list command arg ..." */
700 len += sizeof(LL_CMND_STR) - 1 + strlen(user_cmnd);
701 if (ISSET(sudo_mode, MODE_CHECK))
702 len += sizeof("list ") - 1;
703 if (user_args != NULL)
704 len += strlen(user_args) + 1;
708 * Allocate and build up the line.
710 line = emalloc(++len);
713 if (message != NULL) {
714 if (strlcat(line, message, len) >= len ||
715 strlcat(line, errstr ? " : " : " ; ", len) >= len)
719 if (strlcat(line, errstr, len) >= len ||
720 strlcat(line, " ; ", len) >= len)
723 if (strlcat(line, LL_TTY_STR, len) >= len ||
724 strlcat(line, user_tty, len) >= len ||
725 strlcat(line, " ; ", len) >= len)
727 if (strlcat(line, LL_CWD_STR, len) >= len ||
728 strlcat(line, user_cwd, len) >= len ||
729 strlcat(line, " ; ", len) >= len)
731 if (runas_pw != NULL) {
732 if (strlcat(line, LL_USER_STR, len) >= len ||
733 strlcat(line, runas_pw->pw_name, len) >= len ||
734 strlcat(line, " ; ", len) >= len)
737 if (runas_gr != NULL) {
738 if (strlcat(line, LL_GROUP_STR, len) >= len ||
739 strlcat(line, runas_gr->gr_name, len) >= len ||
740 strlcat(line, " ; ", len) >= len)
744 if (strlcat(line, LL_TSID_STR, len) >= len ||
745 strlcat(line, tsid, len) >= len ||
746 strlcat(line, " ; ", len) >= len)
750 if (strlcat(line, LL_ENV_STR, len) >= len ||
751 strlcat(line, evstr, len) >= len ||
752 strlcat(line, " ; ", len) >= len)
756 if (user_cmnd != NULL) {
757 if (strlcat(line, LL_CMND_STR, len) >= len)
759 if (ISSET(sudo_mode, MODE_CHECK) && strlcat(line, "list ", len) >= len)
761 if (strlcat(line, user_cmnd, len) >= len)
763 if (user_args != NULL) {
764 if (strlcat(line, " ", len) >= len ||
765 strlcat(line, user_args, len) >= len)
772 errorx(1, "internal error: insufficient space for log line");