Imported Debian patch 1.6.9p11-1
[debian/sudo] / logging.c
1 /*
2  * Copyright (c) 1994-1996,1998-2007 Todd C. Miller <Todd.Miller@courtesan.com>
3  *
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.
7  *
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.
15  *
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.
19  */
20
21 #ifdef __TANDEM
22 # include <floss.h>
23 #endif
24
25 #include <config.h>
26
27 #include <sys/types.h>
28 #include <sys/param.h>
29 #include <sys/stat.h>
30 #include <sys/wait.h>
31 #include <stdio.h>
32 #ifdef STDC_HEADERS
33 # include <stdlib.h>
34 # include <stddef.h>
35 #else
36 # ifdef HAVE_STDLIB_H
37 #  include <stdlib.h>
38 # endif
39 #endif /* STDC_HEADERS */
40 #ifdef HAVE_STRING_H
41 # include <string.h>
42 #else
43 # ifdef HAVE_STRINGS_H
44 #  include <strings.h>
45 # endif
46 #endif /* HAVE_STRING_H */
47 #ifdef HAVE_UNISTD_H
48 # include <unistd.h>
49 #endif /* HAVE_UNISTD_H */
50 #ifdef HAVE_ERR_H
51 # include <err.h>
52 #else
53 # include "emul/err.h"
54 #endif /* HAVE_ERR_H */
55 #include <pwd.h>
56 #include <signal.h>
57 #include <time.h>
58 #include <errno.h>
59
60 #include "sudo.h"
61
62 #ifndef lint
63 __unused static const char rcsid[] = "$Sudo: logging.c,v 1.168.2.13 2007/11/25 13:07:38 millert Exp $";
64 #endif /* lint */
65
66 static void do_syslog           __P((int, char *));
67 static void do_logfile          __P((char *));
68 static void send_mail           __P((char *));
69 static void mail_auth           __P((int, char *));
70 static char *get_timestr        __P((void));
71 static void mysyslog            __P((int, const char *, ...));
72
73 #define MAXSYSLOGTRIES  16      /* num of retries for broken syslogs */
74
75 /*
76  * We do an openlog(3)/closelog(3) for each message because some
77  * authentication methods (notably PAM) use syslog(3) for their
78  * own nefarious purposes and may call openlog(3) and closelog(3).
79  * Note that because we don't want to assume that all systems have
80  * vsyslog(3) (HP-UX doesn't) "%m" will not be expanded.
81  * Sadly this is a maze of #ifdefs.
82  */
83 static void
84 #ifdef __STDC__
85 mysyslog(int pri, const char *fmt, ...)
86 #else
87 mysyslog(pri, fmt, va_alist)
88     int pri;
89     const char *fmt;
90     va_dcl
91 #endif
92 {
93 #ifdef BROKEN_SYSLOG
94     int i;
95 #endif
96     char buf[MAXSYSLOGLEN+1];
97     va_list ap;
98
99 #ifdef __STDC__
100     va_start(ap, fmt);
101 #else
102     va_start(ap);
103 #endif
104 #ifdef LOG_NFACILITIES
105     openlog("sudo", 0, def_syslog);
106 #else
107     openlog("sudo", 0);
108 #endif
109     vsnprintf(buf, sizeof(buf), fmt, ap);
110 #ifdef BROKEN_SYSLOG
111     /*
112      * Some versions of syslog(3) don't guarantee success and return
113      * an int (notably HP-UX < 10.0).  So, if at first we don't succeed,
114      * try, try again...
115      */
116     for (i = 0; i < MAXSYSLOGTRIES; i++)
117         if (syslog(pri, "%s", buf) == 0)
118             break;
119 #else
120     syslog(pri, "%s", buf);
121 #endif /* BROKEN_SYSLOG */
122     va_end(ap);
123     closelog();
124 }
125
126 /*
127  * Log a message to syslog, pre-pending the username and splitting the
128  * message into parts if it is longer than MAXSYSLOGLEN.
129  */
130 static void
131 do_syslog(pri, msg)
132     int pri;
133     char *msg;
134 {
135     size_t len, maxlen;
136     char *p, *tmp, save;
137     const char *fmt;
138     const char *fmt_first = "%8s : %s";
139     const char *fmt_contd = "%8s : (command continued) %s";
140
141     /*
142      * Log the full line, breaking into multiple syslog(3) calls if necessary
143      */
144     fmt = fmt_first;
145     maxlen = MAXSYSLOGLEN - (sizeof(fmt_first) - 6 + strlen(user_name));
146     for (p = msg; *p != '\0'; ) {
147         len = strlen(p);
148         if (len > maxlen) {
149             /*
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.
152              */
153             tmp = memrchr(p, ' ', maxlen);
154             if (tmp == NULL)
155                 tmp = p + maxlen;
156
157             /* NULL terminate line, but save the char to restore later */
158             save = *tmp;
159             *tmp = '\0';
160
161             mysyslog(pri, fmt, user_name, p);
162
163             *tmp = save;                        /* restore saved character */
164
165             /* Advance p and eliminate leading whitespace */
166             for (p = tmp; *p == ' '; p++)
167                 ;
168         } else {
169             mysyslog(pri, fmt, user_name, p);
170             p += len;
171         }
172         fmt = fmt_contd;
173         maxlen = MAXSYSLOGLEN - (sizeof(fmt_contd) - 6 + strlen(user_name));
174     }
175 }
176
177 static void
178 do_logfile(msg)
179     char *msg;
180 {
181     char *full_line;
182     char *beg, *oldend, *end;
183     FILE *fp;
184     mode_t oldmask;
185     size_t maxlen;
186
187     oldmask = umask(077);
188     maxlen = def_loglinelen > 0 ? def_loglinelen : 0;
189     fp = fopen(def_logfile, "a");
190     (void) umask(oldmask);
191     if (fp == NULL) {
192         easprintf(&full_line, "Can't open log file: %s: %s",
193             def_logfile, strerror(errno));
194         send_mail(full_line);
195         efree(full_line);
196     } else if (!lock_file(fileno(fp), SUDO_LOCK)) {
197         easprintf(&full_line, "Can't lock log file: %s: %s",
198             def_logfile, strerror(errno));
199         send_mail(full_line);
200         efree(full_line);
201     } else {
202         if (def_loglinelen == 0) {
203             /* Don't pretty-print long log file lines (hard to grep) */
204             if (def_log_host)
205                 (void) fprintf(fp, "%s : %s : HOST=%s : %s\n", get_timestr(),
206                     user_name, user_shost, msg);
207             else
208                 (void) fprintf(fp, "%s : %s : %s\n", get_timestr(),
209                     user_name, msg);
210         } else {
211             if (def_log_host)
212                 easprintf(&full_line, "%s : %s : HOST=%s : %s", get_timestr(),
213                     user_name, user_shost, msg);
214             else
215                 easprintf(&full_line, "%s : %s : %s", get_timestr(),
216                     user_name, msg);
217
218             /*
219              * Print out full_line with word wrap
220              */
221             beg = end = full_line;
222             while (beg) {
223                 oldend = end;
224                 end = strchr(oldend, ' ');
225
226                 if (maxlen > 0 && end) {
227                     *end = '\0';
228                     if (strlen(beg) > maxlen) {
229                         /* too far, need to back up & print the line */
230
231                         if (beg == (char *)full_line)
232                             maxlen -= 4;        /* don't indent first line */
233
234                         *end = ' ';
235                         if (oldend != beg) {
236                             /* rewind & print */
237                             end = oldend-1;
238                             while (*end == ' ')
239                                 --end;
240                             *(++end) = '\0';
241                             (void) fprintf(fp, "%s\n    ", beg);
242                             *end = ' ';
243                         } else {
244                             (void) fprintf(fp, "%s\n    ", beg);
245                         }
246
247                         /* reset beg to point to the start of the new substr */
248                         beg = end;
249                         while (*beg == ' ')
250                             ++beg;
251                     } else {
252                         /* we still have room */
253                         *end = ' ';
254                     }
255
256                     /* remove leading whitespace */
257                     while (*end == ' ')
258                         ++end;
259                 } else {
260                     /* final line */
261                     (void) fprintf(fp, "%s\n", beg);
262                     beg = NULL;                 /* exit condition */
263                 }
264             }
265             efree(full_line);
266         }
267         (void) fflush(fp);
268         (void) lock_file(fileno(fp), SUDO_UNLOCK);
269         (void) fclose(fp);
270     }
271 }
272
273 /*
274  * Two main functions, log_error() to log errors and log_auth() to
275  * log allow/deny messages.
276  */
277 void
278 log_auth(status, inform_user)
279     int status;
280     int inform_user;
281 {
282     char *evstr = NULL;
283     char *message;
284     char *logline;
285     int pri;
286
287     if (ISSET(status, VALIDATE_OK))
288         pri = def_syslog_goodpri;
289     else
290         pri = def_syslog_badpri;
291
292     /* Set error message, if any. */
293     if (ISSET(status, VALIDATE_OK))
294         message = "";
295     else if (ISSET(status, FLAG_NO_USER))
296         message = "user NOT in sudoers ; ";
297     else if (ISSET(status, FLAG_NO_HOST))
298         message = "user NOT authorized on host ; ";
299     else if (ISSET(status, VALIDATE_NOT_OK))
300         message = "command not allowed ; ";
301     else
302         message = "unknown error ; ";
303
304     if (sudo_user.env_vars != NULL) {
305         size_t len = 7; /* " ; ENV=" */
306         struct list_member *cur;
307         for (cur = sudo_user.env_vars; cur != NULL; cur = cur->next)
308             len += strlen(cur->value) + 1;
309         evstr = emalloc(len);
310         strlcpy(evstr, " ; ENV=", len);
311         for (cur = sudo_user.env_vars; cur != NULL; cur = cur->next) {
312             strlcat(evstr, cur->value, len);
313             strlcat(evstr, " ", len);           /* NOTE: last one will fail */
314         }
315     }
316     easprintf(&logline, "%sTTY=%s ; PWD=%s ; USER=%s%s ; COMMAND=%s%s%s",
317         message, user_tty, user_cwd, *user_runas, evstr ? evstr : "",
318         user_cmnd, user_args ? " " : "", user_args ? user_args : "");
319
320     mail_auth(status, logline);         /* send mail based on status */
321
322     /* Inform the user if they failed to authenticate.  */
323     if (inform_user && ISSET(status, VALIDATE_NOT_OK)) {
324         if (ISSET(status, FLAG_NO_USER))
325             (void) fprintf(stderr, "%s is not in the sudoers file.  %s",
326                 user_name, "This incident will be reported.\n");
327         else if (ISSET(status, FLAG_NO_HOST))
328             (void) fprintf(stderr, "%s is not allowed to run sudo on %s.  %s",
329                 user_name, user_shost, "This incident will be reported.\n");
330         else if (ISSET(status, FLAG_NO_CHECK))
331             (void) fprintf(stderr, "Sorry, user %s may not run sudo on %s.\n",
332                 user_name, user_shost);
333         else
334             (void) fprintf(stderr,
335                 "Sorry, user %s is not allowed to execute '%s%s%s' as %s on %s.\n",
336                 user_name, user_cmnd, user_args ? " " : "",
337                 user_args ? user_args : "", *user_runas, user_host);
338     }
339
340     /*
341      * Log via syslog and/or a file.
342      */
343     if (def_syslog)
344         do_syslog(pri, logline);
345     if (def_logfile)
346         do_logfile(logline);
347
348     efree(evstr);
349     efree(logline);
350 }
351
352 void
353 #ifdef __STDC__
354 log_error(int flags, const char *fmt, ...)
355 #else
356 log_error(flags, fmt, va_alist)
357     int flags;
358     const char *fmt;
359     va_dcl
360 #endif
361 {
362     int serrno = errno;
363     char *message;
364     char *logline;
365     char *evstr = NULL;
366     va_list ap;
367 #ifdef __STDC__
368     va_start(ap, fmt);
369 #else
370     va_start(ap);
371 #endif
372
373     /* Become root if we are not already to avoid user interference */
374     set_perms(PERM_ROOT);
375
376     /* Expand printf-style format + args. */
377     evasprintf(&message, fmt, ap);
378     va_end(ap);
379
380     if (sudo_user.env_vars != NULL) {
381         size_t len = 7; /* " ; ENV=" */
382         struct list_member *cur;
383         for (cur = sudo_user.env_vars; cur != NULL; cur = cur->next)
384             len += strlen(cur->value) + 1;
385         evstr = emalloc(len);
386         strlcpy(evstr, " ; ENV=", len);
387         for (cur = sudo_user.env_vars; cur != NULL; cur = cur->next) {
388             strlcat(evstr, cur->value, len);
389             strlcat(evstr, " ", len);           /* NOTE: last one will fail */
390         }
391     }
392
393     if (ISSET(flags, MSG_ONLY))
394         logline = message;
395     else if (ISSET(flags, USE_ERRNO)) {
396         if (user_args) {
397             easprintf(&logline,
398                 "%s: %s ; TTY=%s ; PWD=%s ; USER=%s%s ; COMMAND=%s %s",
399                 message, strerror(serrno), user_tty, user_cwd, *user_runas,
400                 evstr ? evstr : "", user_cmnd, user_args);
401         } else {
402             easprintf(&logline,
403                 "%s: %s ; TTY=%s ; PWD=%s ; USER=%s%s ; COMMAND=%s", message,
404                 strerror(serrno), user_tty, user_cwd, *user_runas,
405                 evstr ? evstr : "", user_cmnd);
406         }
407     } else {
408         if (user_args) {
409             easprintf(&logline,
410                 "%s ; TTY=%s ; PWD=%s ; USER=%s%s ; COMMAND=%s %s", message,
411                 user_tty, user_cwd, *user_runas, evstr ? evstr : "",
412                 user_cmnd, user_args);
413         } else {
414             easprintf(&logline,
415                 "%s ; TTY=%s ; PWD=%s ; USER=%s%s ; COMMAND=%s", message,
416                 user_tty, user_cwd, *user_runas, evstr ? evstr : "", user_cmnd);
417         }
418     }
419
420     /*
421      * Tell the user.
422      */
423     if (ISSET(flags, USE_ERRNO))
424         warn("%s", message);
425     else
426         warnx("%s", message);
427
428     /*
429      * Send a copy of the error via mail.
430      */
431     if (!ISSET(flags, NO_MAIL))
432         send_mail(logline);
433
434     /*
435      * Log to syslog and/or a file.
436      */
437     if (def_syslog)
438         do_syslog(def_syslog_badpri, logline);
439     if (def_logfile)
440         do_logfile(logline);
441
442     efree(message);
443     if (logline != message)
444         efree(logline);
445
446     if (!ISSET(flags, NO_EXIT))
447         exit(1);
448 }
449
450 #define MAX_MAILFLAGS   63
451
452 /*
453  * Send a message to MAILTO user
454  */
455 static void
456 send_mail(line)
457     char *line;
458 {
459     FILE *mail;
460     char *p;
461     int pfd[2];
462     pid_t pid;
463     sigset_t set, oset;
464 #ifndef NO_ROOT_MAILER
465     static char *root_envp[] = {
466         "HOME=/",
467         "PATH=/usr/bin:/bin",
468         "LOGNAME=root",
469         "USERNAME=root",
470         "USER=root",
471         NULL
472     };
473 #endif
474
475     /* Just return if mailer is disabled. */
476     if (!def_mailerpath || !def_mailto)
477         return;
478
479     (void) sigemptyset(&set);
480     (void) sigaddset(&set, SIGCHLD);
481     (void) sigprocmask(SIG_BLOCK, &set, &oset);
482
483     if (pipe(pfd) == -1)
484         err(1, "cannot open pipe");
485
486     switch (pid = fork()) {
487         case -1:
488             /* Error. */
489             err(1, "cannot fork");
490             break;
491         case 0:
492             {
493                 char *argv[MAX_MAILFLAGS + 1];
494                 char *mpath, *mflags;
495                 int i;
496
497                 /* Child, set stdin to output side of the pipe */
498                 if (pfd[0] != STDIN_FILENO) {
499                     (void) dup2(pfd[0], STDIN_FILENO);
500                     (void) close(pfd[0]);
501                 }
502                 (void) close(pfd[1]);
503
504                 /* Build up an argv based the mailer path and flags */
505                 mflags = estrdup(def_mailerflags);
506                 mpath = estrdup(def_mailerpath);
507                 if ((argv[0] = strrchr(mpath, ' ')))
508                     argv[0]++;
509                 else
510                     argv[0] = mpath;
511
512                 i = 1;
513                 if ((p = strtok(mflags, " \t"))) {
514                     do {
515                         argv[i] = p;
516                     } while (++i < MAX_MAILFLAGS && (p = strtok(NULL, " \t")));
517                 }
518                 argv[i] = NULL;
519
520                 /* Close password file so we don't leak the fd. */
521                 endpwent();
522
523                 /*
524                  * Depending on the config, either run the mailer as root
525                  * (so user cannot kill it) or as the user (for the paranoid).
526                  */
527 #ifndef NO_ROOT_MAILER
528                 set_perms(PERM_ROOT);
529                 execve(mpath, argv, root_envp);
530 #else
531                 set_perms(PERM_FULL_USER);
532                 execv(mpath, argv);
533 #endif /* NO_ROOT_MAILER */
534                 _exit(127);
535             }
536             break;
537     }
538
539     (void) close(pfd[0]);
540     mail = fdopen(pfd[1], "w");
541
542     /* Pipes are all setup, send message via sendmail. */
543     (void) fprintf(mail, "To: %s\nFrom: %s\nAuto-Submitted: %s\nSubject: ",
544         def_mailto, user_name, "auto-generated");
545     for (p = def_mailsub; *p; p++) {
546         /* Expand escapes in the subject */
547         if (*p == '%' && *(p+1) != '%') {
548             switch (*(++p)) {
549                 case 'h':
550                     (void) fputs(user_host, mail);
551                     break;
552                 case 'u':
553                     (void) fputs(user_name, mail);
554                     break;
555                 default:
556                     p--;
557                     break;
558             }
559         } else
560             (void) fputc(*p, mail);
561     }
562     (void) fprintf(mail, "\n\n%s : %s : %s : %s\n\n", user_host,
563         get_timestr(), user_name, line);
564     fclose(mail);
565
566     (void) sigprocmask(SIG_SETMASK, &oset, NULL);
567     /* If mailer is done, wait for it now.  If not, we'll get it later.  */
568     reapchild(SIGCHLD);
569 }
570
571 /*
572  * Send mail based on the value of "status" and compile-time options.
573  */
574 static void
575 mail_auth(status, line)
576     int status;
577     char *line;
578 {
579     int mail_mask;
580
581     /* If any of these bits are set in status, we send mail. */
582     if (def_mail_always)
583         mail_mask =
584             VALIDATE_ERROR|VALIDATE_OK|FLAG_NO_USER|FLAG_NO_HOST|VALIDATE_NOT_OK;
585     else {
586         mail_mask = VALIDATE_ERROR;
587         if (def_mail_no_user)
588             SET(mail_mask, FLAG_NO_USER);
589         if (def_mail_no_host)
590             SET(mail_mask, FLAG_NO_HOST);
591         if (def_mail_no_perms)
592             SET(mail_mask, VALIDATE_NOT_OK);
593     }
594
595     if ((status & mail_mask) != 0)
596         send_mail(line);
597 }
598
599 /*
600  * SIGCHLD sig handler--wait for children as they die.
601  */
602 RETSIGTYPE
603 reapchild(sig)
604     int sig;
605 {
606     int status, serrno = errno;
607 #ifdef sudo_waitpid
608     pid_t pid;
609
610     do {
611         pid = sudo_waitpid(-1, &status, WNOHANG);
612     } while (pid != 0 && (pid != -1 || errno == EINTR));
613 #else
614     (void) wait(&status);
615 #endif
616     errno = serrno;
617 }
618
619 /*
620  * Return an ascii string with the current date + time
621  * Uses strftime() if available, else falls back to ctime().
622  */
623 static char *
624 get_timestr()
625 {
626     char *s;
627     time_t now = time((time_t) 0);
628 #ifdef HAVE_STRFTIME
629     static char buf[128];
630     struct tm *timeptr;
631
632     timeptr = localtime(&now);
633     if (def_log_year)
634         s = "%h %e %T %Y";
635     else
636         s = "%h %e %T";
637
638     /* strftime() does not guarantee to NUL-terminate so we must check. */
639     buf[sizeof(buf) - 1] = '\0';
640     if (strftime(buf, sizeof(buf), s, timeptr) && buf[sizeof(buf) - 1] == '\0')
641         return(buf);
642
643 #endif /* HAVE_STRFTIME */
644
645     s = ctime(&now) + 4;                /* skip day of the week */
646     if (def_log_year)
647         s[20] = '\0';                   /* avoid the newline */
648     else
649         s[15] = '\0';                   /* don't care about year */
650
651     return(s);
652 }