2 * Copyright (c) 1994-1996, 1998-2009 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 */
44 # ifdef HAVE_STRINGS_H
47 #endif /* HAVE_STRING_H */
50 #endif /* HAVE_UNISTD_H */
60 static void do_syslog __P((int, char *));
61 static void do_logfile __P((char *));
62 static void send_mail __P((char *));
63 static int should_mail __P((int));
64 static char *get_timestr __P((void));
65 static void mysyslog __P((int, const char *, ...));
66 static char *new_logline __P((const char *, int));
68 #define MAXSYSLOGTRIES 16 /* num of retries for broken syslogs */
71 * We do an openlog(3)/closelog(3) for each message because some
72 * authentication methods (notably PAM) use syslog(3) for their
73 * own nefarious purposes and may call openlog(3) and closelog(3).
74 * Note that because we don't want to assume that all systems have
75 * vsyslog(3) (HP-UX doesn't) "%m" will not be expanded.
76 * Sadly this is a maze of #ifdefs.
80 mysyslog(int pri, const char *fmt, ...)
82 mysyslog(pri, fmt, va_alist)
91 char buf[MAXSYSLOGLEN+1];
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 */
121 #define FMT_FIRST "%8s : %s"
122 #define FMT_CONTD "%8s : (command continued) %s"
125 * Log a message to syslog, pre-pending the username and splitting the
126 * message into parts if it is longer than MAXSYSLOGLEN.
138 * Log the full line, breaking into multiple syslog(3) calls if necessary
141 maxlen = MAXSYSLOGLEN - (sizeof(FMT_FIRST) - 6 + strlen(user_name));
142 for (p = msg; *p != '\0'; ) {
146 * Break up the line into what will fit on one syslog(3) line
147 * Try to avoid breaking words into several lines if possible.
149 tmp = memrchr(p, ' ', maxlen);
153 /* NULL terminate line, but save the char to restore later */
157 mysyslog(pri, fmt, user_name, p);
159 *tmp = save; /* restore saved character */
161 /* Advance p and eliminate leading whitespace */
162 for (p = tmp; *p == ' '; p++)
165 mysyslog(pri, fmt, user_name, p);
169 maxlen = MAXSYSLOGLEN - (sizeof(FMT_CONTD) - 6 + strlen(user_name));
178 char *beg, *oldend, *end;
183 oldmask = umask(077);
184 maxlen = def_loglinelen > 0 ? def_loglinelen : 0;
185 fp = fopen(def_logfile, "a");
186 (void) umask(oldmask);
188 easprintf(&full_line, "Can't open log file: %s: %s",
189 def_logfile, strerror(errno));
190 send_mail(full_line);
192 } else if (!lock_file(fileno(fp), SUDO_LOCK)) {
193 easprintf(&full_line, "Can't lock log file: %s: %s",
194 def_logfile, strerror(errno));
195 send_mail(full_line);
198 if (def_loglinelen == 0) {
199 /* Don't pretty-print long log file lines (hard to grep) */
201 (void) fprintf(fp, "%s : %s : HOST=%s : %s\n", get_timestr(),
202 user_name, user_shost, msg);
204 (void) fprintf(fp, "%s : %s : %s\n", get_timestr(),
208 easprintf(&full_line, "%s : %s : HOST=%s : %s", get_timestr(),
209 user_name, user_shost, msg);
211 easprintf(&full_line, "%s : %s : %s", get_timestr(),
215 * Print out full_line with word wrap
217 beg = end = full_line;
220 end = strchr(oldend, ' ');
222 if (maxlen > 0 && end) {
224 if (strlen(beg) > maxlen) {
225 /* too far, need to back up & print the line */
227 if (beg == (char *)full_line)
228 maxlen -= 4; /* don't indent first line */
237 (void) fprintf(fp, "%s\n ", beg);
240 (void) fprintf(fp, "%s\n ", beg);
243 /* reset beg to point to the start of the new substr */
248 /* we still have room */
252 /* remove leading whitespace */
257 (void) fprintf(fp, "%s\n", beg);
258 beg = NULL; /* exit condition */
264 (void) lock_file(fileno(fp), SUDO_UNLOCK);
270 * Log and mail the denial message, optionally informing the user.
273 log_denial(status, inform_user)
280 /* Set error message. */
281 if (ISSET(status, FLAG_NO_USER))
282 message = "user NOT in sudoers";
283 else if (ISSET(status, FLAG_NO_HOST))
284 message = "user NOT authorized on host";
286 message = "command not allowed";
288 logline = new_logline(message, 0);
290 if (should_mail(status))
291 send_mail(logline); /* send mail based on status */
293 /* Inform the user if they failed to authenticate. */
295 if (ISSET(status, FLAG_NO_USER))
296 (void) fprintf(stderr, "%s is not in the sudoers file. %s",
297 user_name, "This incident will be reported.\n");
298 else if (ISSET(status, FLAG_NO_HOST))
299 (void) fprintf(stderr, "%s is not allowed to run sudo on %s. %s",
300 user_name, user_shost, "This incident will be reported.\n");
301 else if (ISSET(status, FLAG_NO_CHECK))
302 (void) fprintf(stderr, "Sorry, user %s may not run sudo on %s.\n",
303 user_name, user_shost);
305 (void) fprintf(stderr,
306 "Sorry, user %s is not allowed to execute '%s%s%s' as %s%s%s on %s.\n",
307 user_name, user_cmnd, user_args ? " " : "",
308 user_args ? user_args : "",
309 list_pw ? list_pw->pw_name : runas_pw ?
310 runas_pw->pw_name : user_name, runas_gr ? ":" : "",
311 runas_gr ? runas_gr->gr_name : "", user_host);
315 * Log via syslog and/or a file.
318 do_syslog(def_syslog_badpri, logline);
326 * Log and potentially mail the allowed command.
334 logline = new_logline(NULL, 0);
336 if (should_mail(status))
337 send_mail(logline); /* send mail based on status */
340 * Log via syslog and/or a file.
343 do_syslog(def_syslog_goodpri, logline);
352 log_error(int flags, const char *fmt, ...)
354 log_error(flags, fmt, va_alist)
370 /* Become root if we are not already to avoid user interference */
371 set_perms(PERM_ROOT|PERM_NOEXIT);
373 /* Expand printf-style format + args. */
374 evasprintf(&message, fmt, ap);
377 if (ISSET(flags, MSG_ONLY))
380 logline = new_logline(message, ISSET(flags, USE_ERRNO) ? serrno : 0);
385 if (!ISSET(flags, NO_STDERR)) {
386 if (ISSET(flags, USE_ERRNO))
387 warning("%s", message);
389 warningx("%s", message);
391 if (logline != message)
395 * Send a copy of the error via mail.
397 if (!ISSET(flags, NO_MAIL))
401 * Log to syslog and/or a file.
404 do_syslog(def_syslog_badpri, logline);
410 if (!ISSET(flags, NO_EXIT)) {
416 #define MAX_MAILFLAGS 63
419 * Send a message to MAILTO user
427 int fd, pfd[2], status;
430 #ifndef NO_ROOT_MAILER
431 static char *root_envp[] = {
433 "PATH=/usr/bin:/bin",
441 /* Just return if mailer is disabled. */
442 if (!def_mailerpath || !def_mailto)
445 /* Fork and return, child will daemonize. */
446 switch (pid = fork()) {
449 error(1, "cannot fork");
453 switch (pid = fork()) {
456 mysyslog(LOG_ERR, "cannot fork: %m");
459 /* Grandchild continues below. */
462 /* Parent will wait for us. */
470 rv = waitpid(pid, &status, 0);
474 } while (rv == -1 && errno == EINTR);
478 /* Daemonize - disassociate from session/tty. */
485 if ((fd = open(_PATH_TTY, O_RDWR, 0644)) != -1) {
486 ioctl(fd, TIOCNOTTY, NULL);
492 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0644)) != -1) {
493 (void) dup2(fd, STDIN_FILENO);
494 (void) dup2(fd, STDOUT_FILENO);
495 (void) dup2(fd, STDERR_FILENO);
498 /* Close password, group and other fds so we don't leak. */
501 closefrom(STDERR_FILENO + 1);
503 /* Ignore SIGPIPE in case mailer exits prematurely (or is missing). */
504 zero_bytes(&sa, sizeof(sa));
505 sigemptyset(&sa.sa_mask);
507 sa.sa_handler = SIG_IGN;
508 (void) sigaction(SIGPIPE, &sa, NULL);
510 if (pipe(pfd) == -1) {
511 mysyslog(LOG_ERR, "cannot open pipe: %m");
515 switch (pid = fork()) {
518 mysyslog(LOG_ERR, "cannot fork: %m");
523 char *argv[MAX_MAILFLAGS + 1];
524 char *mpath, *mflags;
527 /* Child, set stdin to output side of the pipe */
528 if (pfd[0] != STDIN_FILENO) {
529 (void) dup2(pfd[0], STDIN_FILENO);
530 (void) close(pfd[0]);
532 (void) close(pfd[1]);
534 /* Build up an argv based the mailer path and flags */
535 mflags = estrdup(def_mailerflags);
536 mpath = estrdup(def_mailerpath);
537 if ((argv[0] = strrchr(mpath, ' ')))
543 if ((p = strtok(mflags, " \t"))) {
546 } while (++i < MAX_MAILFLAGS && (p = strtok(NULL, " \t")));
551 * Depending on the config, either run the mailer as root
552 * (so user cannot kill it) or as the user (for the paranoid).
554 #ifndef NO_ROOT_MAILER
555 set_perms(PERM_ROOT|PERM_NOEXIT);
556 execve(mpath, argv, root_envp);
558 set_perms(PERM_FULL_USER|PERM_NOEXIT);
560 #endif /* NO_ROOT_MAILER */
561 mysyslog(LOG_ERR, "cannot execute %s: %m", mpath);
567 (void) close(pfd[0]);
568 mail = fdopen(pfd[1], "w");
570 /* Pipes are all setup, send message. */
571 (void) fprintf(mail, "To: %s\nFrom: %s\nAuto-Submitted: %s\nSubject: ",
572 def_mailto, def_mailfrom ? def_mailfrom : user_name, "auto-generated");
573 for (p = def_mailsub; *p; p++) {
574 /* Expand escapes in the subject */
575 if (*p == '%' && *(p+1) != '%') {
578 (void) fputs(user_host, mail);
581 (void) fputs(user_name, mail);
588 (void) fputc(*p, mail);
590 (void) fprintf(mail, "\n\n%s : %s : %s : %s\n\n", user_host,
591 get_timestr(), user_name, line);
595 rv = waitpid(pid, &status, 0);
599 } while (rv == -1 && errno == EINTR);
604 * Determine whether we should send mail based on "status" and defaults options.
611 return(def_mail_always || ISSET(status, VALIDATE_ERROR) ||
612 (def_mail_no_user && ISSET(status, FLAG_NO_USER)) ||
613 (def_mail_no_host && ISSET(status, FLAG_NO_HOST)) ||
614 (def_mail_no_perms && !ISSET(status, VALIDATE_OK)));
618 * Return an ascii string with the current date + time
619 * Uses strftime() if available, else falls back to ctime().
625 time_t now = time((time_t) 0);
627 static char buf[128];
630 timeptr = localtime(&now);
636 /* strftime() does not guarantee to NUL-terminate so we must check. */
637 buf[sizeof(buf) - 1] = '\0';
638 if (strftime(buf, sizeof(buf), s, timeptr) && buf[sizeof(buf) - 1] == '\0')
641 #endif /* HAVE_STRFTIME */
643 s = ctime(&now) + 4; /* skip day of the week */
645 s[20] = '\0'; /* avoid the newline */
647 s[15] = '\0'; /* don't care about year */
652 #define LL_TTY_STR "TTY="
653 #define LL_CWD_STR "PWD=" /* XXX - should be CWD= */
654 #define LL_USER_STR "USER="
655 #define LL_GROUP_STR "GROUP="
656 #define LL_ENV_STR "ENV="
657 #define LL_CMND_STR "COMMAND="
660 * Allocate and fill in a new logline.
663 new_logline(message, serrno)
673 * Compute line length
676 len += strlen(message) + 3;
678 errstr = strerror(serrno);
679 len += strlen(errstr) + 3;
681 len += sizeof(LL_TTY_STR) + 2 + strlen(user_tty);
682 len += sizeof(LL_CWD_STR) + 2 + strlen(user_cwd);
683 if (runas_pw != NULL)
684 len += sizeof(LL_USER_STR) + 2 + strlen(runas_pw->pw_name);
685 if (runas_gr != NULL)
686 len += sizeof(LL_GROUP_STR) + 2 + strlen(runas_gr->gr_name);
687 if (sudo_user.env_vars != NULL) {
689 struct list_member *cur;
690 for (cur = sudo_user.env_vars; cur != NULL; cur = cur->next)
691 evlen += strlen(cur->value) + 1;
692 evstr = emalloc(evlen);
694 for (cur = sudo_user.env_vars; cur != NULL; cur = cur->next) {
695 strlcat(evstr, cur->value, evlen);
696 strlcat(evstr, " ", evlen); /* NOTE: last one will fail */
698 len += sizeof(LL_ENV_STR) + 2 + evlen;
700 len += sizeof(LL_CMND_STR) - 1 + strlen(user_cmnd);
701 if (user_args != NULL)
702 len += strlen(user_args) + 1;
705 * Allocate and build up the line.
707 line = emalloc(++len);
710 if (message != NULL) {
711 if (strlcat(line, message, len) >= len ||
712 strlcat(line, errstr ? " : " : " ; ", len) >= len)
716 if (strlcat(line, errstr, len) >= len ||
717 strlcat(line, " ; ", len) >= len)
720 if (strlcat(line, LL_TTY_STR, len) >= len ||
721 strlcat(line, user_tty, len) >= len ||
722 strlcat(line, " ; ", len) >= len)
724 if (strlcat(line, LL_CWD_STR, len) >= len ||
725 strlcat(line, user_cwd, len) >= len ||
726 strlcat(line, " ; ", len) >= len)
728 if (runas_pw != NULL) {
729 if (strlcat(line, LL_USER_STR, len) >= len ||
730 strlcat(line, runas_pw->pw_name, len) >= len ||
731 strlcat(line, " ; ", len) >= len)
734 if (runas_gr != NULL) {
735 if (strlcat(line, LL_GROUP_STR, len) >= len ||
736 strlcat(line, runas_gr->gr_name, len) >= len ||
737 strlcat(line, " ; ", len) >= len)
741 if (strlcat(line, LL_ENV_STR, len) >= len ||
742 strlcat(line, evstr, len) >= len ||
743 strlcat(line, " ; ", len) >= len)
747 if (strlcat(line, LL_CMND_STR, len) >= len ||
748 strlcat(line, user_cmnd, len) >= len)
750 if (user_args != NULL) {
751 if (strlcat(line, " ", len) >= len ||
752 strlcat(line, user_args, len) >= len)
758 errorx(1, "internal error: insufficient space for log line");