Merge commit 'upstream/1.7.4p6'
[debian/sudo] / logging.c
1 /*
2  * Copyright (c) 1994-1996, 1998-2010 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/ioctl.h>
31 #include <sys/wait.h>
32 #include <stdio.h>
33 #ifdef STDC_HEADERS
34 # include <stdlib.h>
35 # include <stddef.h>
36 #else
37 # ifdef HAVE_STDLIB_H
38 #  include <stdlib.h>
39 # endif
40 #endif /* STDC_HEADERS */
41 #ifdef HAVE_STRING_H
42 # include <string.h>
43 #endif /* HAVE_STRING_H */
44 #ifdef HAVE_STRINGS_H
45 # include <strings.h>
46 #endif /* HAVE_STRINGS_H */
47 #ifdef HAVE_UNISTD_H
48 # include <unistd.h>
49 #endif /* HAVE_UNISTD_H */
50 #include <pwd.h>
51 #include <grp.h>
52 #include <signal.h>
53 #include <time.h>
54 #include <errno.h>
55 #include <fcntl.h>
56
57 #include "sudo.h"
58
59 static void do_syslog           __P((int, char *));
60 static void do_logfile          __P((char *));
61 static void send_mail           __P((const char *fmt, ...));
62 static int should_mail          __P((int));
63 static void mysyslog            __P((int, const char *, ...));
64 static char *new_logline        __P((const char *, int));
65
66 #define MAXSYSLOGTRIES  16      /* num of retries for broken syslogs */
67
68 /*
69  * We do an openlog(3)/closelog(3) for each message because some
70  * authentication methods (notably PAM) use syslog(3) for their
71  * own nefarious purposes and may call openlog(3) and closelog(3).
72  * Note that because we don't want to assume that all systems have
73  * vsyslog(3) (HP-UX doesn't) "%m" will not be expanded.
74  * Sadly this is a maze of #ifdefs.
75  */
76 static void
77 #ifdef __STDC__
78 mysyslog(int pri, const char *fmt, ...)
79 #else
80 mysyslog(pri, fmt, va_alist)
81     int pri;
82     const char *fmt;
83     va_dcl
84 #endif
85 {
86 #ifdef BROKEN_SYSLOG
87     int i;
88 #endif
89     char buf[MAXSYSLOGLEN+1];
90     va_list ap;
91
92 #ifdef __STDC__
93     va_start(ap, fmt);
94 #else
95     va_start(ap);
96 #endif
97 #ifdef LOG_NFACILITIES
98     openlog("sudo", 0, def_syslog);
99 #else
100     openlog("sudo", 0);
101 #endif
102     vsnprintf(buf, sizeof(buf), fmt, ap);
103 #ifdef BROKEN_SYSLOG
104     /*
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,
107      * try, try again...
108      */
109     for (i = 0; i < MAXSYSLOGTRIES; i++)
110         if (syslog(pri, "%s", buf) == 0)
111             break;
112 #else
113     syslog(pri, "%s", buf);
114 #endif /* BROKEN_SYSLOG */
115     va_end(ap);
116     closelog();
117 }
118
119 #define FMT_FIRST "%8s : %s"
120 #define FMT_CONTD "%8s : (command continued) %s"
121
122 /*
123  * Log a message to syslog, pre-pending the username and splitting the
124  * message into parts if it is longer than MAXSYSLOGLEN.
125  */
126 static void
127 do_syslog(pri, msg)
128     int pri;
129     char *msg;
130 {
131     size_t len, maxlen;
132     char *p, *tmp, save;
133     const char *fmt;
134
135     /*
136      * Log the full line, breaking into multiple syslog(3) calls if necessary
137      */
138     fmt = FMT_FIRST;
139     maxlen = MAXSYSLOGLEN - (sizeof(FMT_FIRST) - 6 + strlen(user_name));
140     for (p = msg; *p != '\0'; ) {
141         len = strlen(p);
142         if (len > maxlen) {
143             /*
144              * Break up the line into what will fit on one syslog(3) line
145              * Try to avoid breaking words into several lines if possible.
146              */
147             tmp = memrchr(p, ' ', maxlen);
148             if (tmp == NULL)
149                 tmp = p + maxlen;
150
151             /* NULL terminate line, but save the char to restore later */
152             save = *tmp;
153             *tmp = '\0';
154
155             mysyslog(pri, fmt, user_name, p);
156
157             *tmp = save;                        /* restore saved character */
158
159             /* Advance p and eliminate leading whitespace */
160             for (p = tmp; *p == ' '; p++)
161                 ;
162         } else {
163             mysyslog(pri, fmt, user_name, p);
164             p += len;
165         }
166         fmt = FMT_CONTD;
167         maxlen = MAXSYSLOGLEN - (sizeof(FMT_CONTD) - 6 + strlen(user_name));
168     }
169 }
170
171 static void
172 do_logfile(msg)
173     char *msg;
174 {
175     char *full_line;
176     char *beg, *oldend, *end;
177     FILE *fp;
178     mode_t oldmask;
179     size_t maxlen;
180
181     oldmask = umask(077);
182     maxlen = def_loglinelen > 0 ? def_loglinelen : 0;
183     fp = fopen(def_logfile, "a");
184     (void) umask(oldmask);
185     if (fp == NULL) {
186         send_mail("Can't open log file: %s: %s", def_logfile, strerror(errno));
187     } else if (!lock_file(fileno(fp), SUDO_LOCK)) {
188         send_mail("Can't lock log file: %s: %s", def_logfile, strerror(errno));
189     } else {
190         time_t now;
191
192         now = time(NULL);
193         if (def_loglinelen == 0) {
194             /* Don't pretty-print long log file lines (hard to grep) */
195             if (def_log_host)
196                 (void) fprintf(fp, "%s : %s : HOST=%s : %s\n",
197                     get_timestr(now, def_log_year), user_name, user_shost, msg);
198             else
199                 (void) fprintf(fp, "%s : %s : %s\n",
200                     get_timestr(now, def_log_year), user_name, msg);
201         } else {
202             if (def_log_host)
203                 easprintf(&full_line, "%s : %s : HOST=%s : %s",
204                     get_timestr(now, def_log_year), user_name, user_shost, msg);
205             else
206                 easprintf(&full_line, "%s : %s : %s",
207                     get_timestr(now, def_log_year), user_name, msg);
208
209             /*
210              * Print out full_line with word wrap
211              */
212             beg = end = full_line;
213             while (beg) {
214                 oldend = end;
215                 end = strchr(oldend, ' ');
216
217                 if (maxlen > 0 && end) {
218                     *end = '\0';
219                     if (strlen(beg) > maxlen) {
220                         /* too far, need to back up & print the line */
221
222                         if (beg == (char *)full_line)
223                             maxlen -= 4;        /* don't indent first line */
224
225                         *end = ' ';
226                         if (oldend != beg) {
227                             /* rewind & print */
228                             end = oldend-1;
229                             while (*end == ' ')
230                                 --end;
231                             *(++end) = '\0';
232                             (void) fprintf(fp, "%s\n    ", beg);
233                             *end = ' ';
234                         } else {
235                             (void) fprintf(fp, "%s\n    ", beg);
236                         }
237
238                         /* reset beg to point to the start of the new substr */
239                         beg = end;
240                         while (*beg == ' ')
241                             ++beg;
242                     } else {
243                         /* we still have room */
244                         *end = ' ';
245                     }
246
247                     /* remove leading whitespace */
248                     while (*end == ' ')
249                         ++end;
250                 } else {
251                     /* final line */
252                     (void) fprintf(fp, "%s\n", beg);
253                     beg = NULL;                 /* exit condition */
254                 }
255             }
256             efree(full_line);
257         }
258         (void) fflush(fp);
259         (void) lock_file(fileno(fp), SUDO_UNLOCK);
260         (void) fclose(fp);
261     }
262 }
263
264 /*
265  * Log and mail the denial message, optionally informing the user.
266  */
267 void
268 log_denial(status, inform_user)
269     int status;
270     int inform_user;
271 {
272     char *message;
273     char *logline;
274
275     /* Set error message. */
276     if (ISSET(status, FLAG_NO_USER))
277         message = "user NOT in sudoers";
278     else if (ISSET(status, FLAG_NO_HOST))
279         message = "user NOT authorized on host";
280     else
281         message = "command not allowed";
282
283     logline = new_logline(message, 0);
284
285     if (should_mail(status))
286         send_mail("%s", logline);       /* send mail based on status */
287
288     /* Inform the user if they failed to authenticate.  */
289     if (inform_user) {
290         if (ISSET(status, FLAG_NO_USER))
291             (void) fprintf(stderr, "%s is not in the sudoers file.  %s",
292                 user_name, "This incident will be reported.\n");
293         else if (ISSET(status, FLAG_NO_HOST))
294             (void) fprintf(stderr, "%s is not allowed to run sudo on %s.  %s",
295                 user_name, user_shost, "This incident will be reported.\n");
296         else if (ISSET(status, FLAG_NO_CHECK))
297             (void) fprintf(stderr, "Sorry, user %s may not run sudo on %s.\n",
298                 user_name, user_shost);
299         else
300             (void) fprintf(stderr,
301                 "Sorry, user %s is not allowed to execute '%s%s%s' as %s%s%s on %s.\n",
302                 user_name, user_cmnd, user_args ? " " : "",
303                 user_args ? user_args : "",
304                 list_pw ? list_pw->pw_name : runas_pw ?
305                 runas_pw->pw_name : user_name, runas_gr ? ":" : "",
306                 runas_gr ? runas_gr->gr_name : "", user_host);
307     }
308
309     /*
310      * Log via syslog and/or a file.
311      */
312     if (def_syslog)
313         do_syslog(def_syslog_badpri, logline);
314     if (def_logfile)
315         do_logfile(logline);
316
317     efree(logline);
318 }
319
320 /*
321  * Log and potentially mail the allowed command.
322  */
323 void
324 log_allowed(status)
325     int status;
326 {
327     char *logline;
328
329     logline = new_logline(NULL, 0);
330
331     if (should_mail(status))
332         send_mail("%s", logline);       /* send mail based on status */
333
334     /*
335      * Log via syslog and/or a file.
336      */
337     if (def_syslog)
338         do_syslog(def_syslog_goodpri, logline);
339     if (def_logfile)
340         do_logfile(logline);
341
342     efree(logline);
343 }
344
345 void
346 #ifdef __STDC__
347 log_error(int flags, const char *fmt, ...)
348 #else
349 log_error(flags, fmt, va_alist)
350     int flags;
351     const char *fmt;
352     va_dcl
353 #endif
354 {
355     int serrno = errno;
356     char *message;
357     char *logline;
358     va_list ap;
359 #ifdef __STDC__
360     va_start(ap, fmt);
361 #else
362     va_start(ap);
363 #endif
364
365     /* Become root if we are not already to avoid user interference */
366     set_perms(PERM_ROOT|PERM_NOEXIT);
367
368     /* Expand printf-style format + args. */
369     evasprintf(&message, fmt, ap);
370     va_end(ap);
371
372     if (ISSET(flags, MSG_ONLY))
373         logline = message;
374     else
375         logline = new_logline(message, ISSET(flags, USE_ERRNO) ? serrno : 0);
376
377     /*
378      * Tell the user.
379      */
380     if (!ISSET(flags, NO_STDERR)) {
381         if (ISSET(flags, USE_ERRNO))
382             warning("%s", message);
383         else
384             warningx("%s", message);
385     }
386     if (logline != message)
387         efree(message);
388
389     /*
390      * Send a copy of the error via mail.
391      */
392     if (!ISSET(flags, NO_MAIL))
393         send_mail("%s", logline);
394
395     /*
396      * Log to syslog and/or a file.
397      */
398     if (def_syslog)
399         do_syslog(def_syslog_badpri, logline);
400     if (def_logfile)
401         do_logfile(logline);
402
403     efree(logline);
404
405     if (!ISSET(flags, NO_EXIT)) {
406         cleanup(0);
407         exit(1);
408     }
409 }
410
411 #define MAX_MAILFLAGS   63
412
413 /*
414  * Send a message to MAILTO user
415  */
416 static void
417 #ifdef __STDC__
418 send_mail(const char *fmt, ...)
419 #else
420 send_mail(fmt, va_alist)
421     const char *fmt;
422     va_dcl
423 #endif
424 {
425     FILE *mail;
426     char *p;
427     int fd, pfd[2], status;
428     pid_t pid, rv;
429     sigaction_t sa;
430     va_list ap;
431 #ifndef NO_ROOT_MAILER
432     static char *root_envp[] = {
433         "HOME=/",
434         "PATH=/usr/bin:/bin:/usr/sbin:/sbin",
435         "LOGNAME=root",
436         "USERNAME=root",
437         "USER=root",
438         NULL
439     };
440 #endif
441
442     /* Just return if mailer is disabled. */
443     if (!def_mailerpath || !def_mailto)
444         return;
445
446     /* Fork and return, child will daemonize. */
447     switch (pid = fork()) {
448         case -1:
449             /* Error. */
450             error(1, "cannot fork");
451             break;
452         case 0:
453             /* Child. */
454             switch (pid = fork()) {
455                 case -1:
456                     /* Error. */
457                     mysyslog(LOG_ERR, "cannot fork: %m");
458                     _exit(1);
459                 case 0:
460                     /* Grandchild continues below. */
461                     break;
462                 default:
463                     /* Parent will wait for us. */
464                     _exit(0);
465             }
466             break;
467         default:
468             /* Parent. */
469             do {
470 #ifdef HAVE_WAITPID
471                 rv = waitpid(pid, &status, 0);
472 #else
473                 rv = wait(&status);
474 #endif
475             } while (rv == -1 && errno == EINTR);
476             return;
477     }
478
479     /* Daemonize - disassociate from session/tty. */
480     if (setsid() == -1)
481       warning("setsid");
482     (void) chdir("/");
483     if ((fd = open(_PATH_DEVNULL, O_RDWR, 0644)) != -1) {
484         (void) dup2(fd, STDIN_FILENO);
485         (void) dup2(fd, STDOUT_FILENO);
486         (void) dup2(fd, STDERR_FILENO);
487     }
488
489     /* Close password, group and other fds so we don't leak. */
490     sudo_endpwent();
491     sudo_endgrent();
492     closefrom(STDERR_FILENO + 1);
493
494     /* Ignore SIGPIPE in case mailer exits prematurely (or is missing). */
495     zero_bytes(&sa, sizeof(sa));
496     sigemptyset(&sa.sa_mask);
497     sa.sa_flags = SA_INTERRUPT;
498     sa.sa_handler = SIG_IGN;
499     (void) sigaction(SIGPIPE, &sa, NULL);
500
501     if (pipe(pfd) == -1) {
502         mysyslog(LOG_ERR, "cannot open pipe: %m");
503         _exit(1);
504     }
505
506     switch (pid = fork()) {
507         case -1:
508             /* Error. */
509             mysyslog(LOG_ERR, "cannot fork: %m");
510             _exit(1);
511             break;
512         case 0:
513             {
514                 char *argv[MAX_MAILFLAGS + 1];
515                 char *mpath, *mflags;
516                 int i;
517
518                 /* Child, set stdin to output side of the pipe */
519                 if (pfd[0] != STDIN_FILENO) {
520                     if (dup2(pfd[0], STDIN_FILENO) == -1) {
521                         mysyslog(LOG_ERR, "cannot dup stdin: %m");
522                         _exit(127);
523                     }
524                     (void) close(pfd[0]);
525                 }
526                 (void) close(pfd[1]);
527
528                 /* Build up an argv based on the mailer path and flags */
529                 mflags = estrdup(def_mailerflags);
530                 mpath = estrdup(def_mailerpath);
531                 if ((argv[0] = strrchr(mpath, ' ')))
532                     argv[0]++;
533                 else
534                     argv[0] = mpath;
535
536                 i = 1;
537                 if ((p = strtok(mflags, " \t"))) {
538                     do {
539                         argv[i] = p;
540                     } while (++i < MAX_MAILFLAGS && (p = strtok(NULL, " \t")));
541                 }
542                 argv[i] = NULL;
543
544                 /*
545                  * Depending on the config, either run the mailer as root
546                  * (so user cannot kill it) or as the user (for the paranoid).
547                  */
548 #ifndef NO_ROOT_MAILER
549                 set_perms(PERM_ROOT|PERM_NOEXIT);
550                 execve(mpath, argv, root_envp);
551 #else
552                 set_perms(PERM_FULL_USER|PERM_NOEXIT);
553                 execv(mpath, argv);
554 #endif /* NO_ROOT_MAILER */
555                 mysyslog(LOG_ERR, "cannot execute %s: %m", mpath);
556                 _exit(127);
557             }
558             break;
559     }
560
561     (void) close(pfd[0]);
562     mail = fdopen(pfd[1], "w");
563
564     /* Pipes are all setup, send message. */
565     (void) fprintf(mail, "To: %s\nFrom: %s\nAuto-Submitted: %s\nSubject: ",
566         def_mailto, def_mailfrom ? def_mailfrom : user_name, "auto-generated");
567     for (p = def_mailsub; *p; p++) {
568         /* Expand escapes in the subject */
569         if (*p == '%' && *(p+1) != '%') {
570             switch (*(++p)) {
571                 case 'h':
572                     (void) fputs(user_host, mail);
573                     break;
574                 case 'u':
575                     (void) fputs(user_name, mail);
576                     break;
577                 default:
578                     p--;
579                     break;
580             }
581         } else
582             (void) fputc(*p, mail);
583     }
584
585     (void) fprintf(mail, "\n\n%s : %s : %s : ", user_host,
586         get_timestr(time(NULL), def_log_year), user_name);
587 #ifdef __STDC__
588     va_start(ap, fmt);
589 #else
590     va_start(ap);
591 #endif
592     (void) vfprintf(mail, fmt, ap);
593     va_end(ap);
594     fputs("\n\n", mail);
595
596     fclose(mail);
597     do {
598 #ifdef HAVE_WAITPID
599         rv = waitpid(pid, &status, 0);
600 #else
601         rv = wait(&status);
602 #endif
603     } while (rv == -1 && errno == EINTR);
604     _exit(0);
605 }
606
607 /*
608  * Determine whether we should send mail based on "status" and defaults options.
609  */
610 static int
611 should_mail(status)
612     int status;
613 {
614
615     return(def_mail_always || ISSET(status, VALIDATE_ERROR) ||
616         (def_mail_no_user && ISSET(status, FLAG_NO_USER)) ||
617         (def_mail_no_host && ISSET(status, FLAG_NO_HOST)) ||
618         (def_mail_no_perms && !ISSET(status, VALIDATE_OK)));
619 }
620
621 #define LL_TTY_STR      "TTY="
622 #define LL_CWD_STR      "PWD="          /* XXX - should be CWD= */
623 #define LL_USER_STR     "USER="
624 #define LL_GROUP_STR    "GROUP="
625 #define LL_ENV_STR      "ENV="
626 #define LL_CMND_STR     "COMMAND="
627 #define LL_TSID_STR     "TSID="
628
629 /*
630  * Allocate and fill in a new logline.
631  */
632 static char *
633 new_logline(message, serrno)
634     const char *message;
635     int serrno;
636 {
637     size_t len = 0;
638     char *evstr = NULL;
639     char *errstr = NULL;
640     char *line;
641
642     /*
643      * Compute line length
644      */
645     if (message != NULL)
646         len += strlen(message) + 3;
647     if (serrno) {
648         errstr = strerror(serrno);
649         len += strlen(errstr) + 3;
650     }
651     len += sizeof(LL_TTY_STR) + 2 + strlen(user_tty);
652     len += sizeof(LL_CWD_STR) + 2 + strlen(user_cwd);
653     if (runas_pw != NULL)
654         len += sizeof(LL_USER_STR) + 2 + strlen(runas_pw->pw_name);
655     if (runas_gr != NULL)
656         len += sizeof(LL_GROUP_STR) + 2 + strlen(runas_gr->gr_name);
657     if (sudo_user.sessid[0] != '\0')
658         len += sizeof(LL_TSID_STR) + 2 + strlen(sudo_user.sessid);
659     if (sudo_user.env_vars != NULL) {
660         size_t evlen = 0;
661         struct list_member *cur;
662         for (cur = sudo_user.env_vars; cur != NULL; cur = cur->next)
663             evlen += strlen(cur->value) + 1;
664         evstr = emalloc(evlen);
665         evstr[0] = '\0';
666         for (cur = sudo_user.env_vars; cur != NULL; cur = cur->next) {
667             strlcat(evstr, cur->value, evlen);
668             strlcat(evstr, " ", evlen); /* NOTE: last one will fail */
669         }
670         len += sizeof(LL_ENV_STR) + 2 + evlen;
671     }
672     len += sizeof(LL_CMND_STR) - 1 + strlen(user_cmnd);
673     if (user_args != NULL)
674         len += strlen(user_args) + 1;
675
676     /*
677      * Allocate and build up the line.
678      */
679     line = emalloc(++len);
680     line[0] = '\0';
681
682     if (message != NULL) {
683         if (strlcat(line, message, len) >= len ||
684             strlcat(line, errstr ? " : " : " ; ", len) >= len)
685             goto toobig;
686     }
687     if (serrno) {
688         if (strlcat(line, errstr, len) >= len ||
689             strlcat(line, " ; ", len) >= len)
690             goto toobig;
691     }
692     if (strlcat(line, LL_TTY_STR, len) >= len ||
693         strlcat(line, user_tty, len) >= len ||
694         strlcat(line, " ; ", len) >= len)
695         goto toobig;
696     if (strlcat(line, LL_CWD_STR, len) >= len ||
697         strlcat(line, user_cwd, len) >= len ||
698         strlcat(line, " ; ", len) >= len)
699         goto toobig;
700     if (runas_pw != NULL) {
701         if (strlcat(line, LL_USER_STR, len) >= len ||
702             strlcat(line, runas_pw->pw_name, len) >= len ||
703             strlcat(line, " ; ", len) >= len)
704             goto toobig;
705     }
706     if (runas_gr != NULL) {
707         if (strlcat(line, LL_GROUP_STR, len) >= len ||
708             strlcat(line, runas_gr->gr_name, len) >= len ||
709             strlcat(line, " ; ", len) >= len)
710             goto toobig;
711     }
712     if (sudo_user.sessid[0] != '\0') {
713         if (strlcat(line, LL_TSID_STR, len) >= len ||
714             strlcat(line, sudo_user.sessid, len) >= len ||
715             strlcat(line, " ; ", len) >= len)
716             goto toobig;
717     }
718     if (evstr != NULL) {
719         if (strlcat(line, LL_ENV_STR, len) >= len ||
720             strlcat(line, evstr, len) >= len ||
721             strlcat(line, " ; ", len) >= len)
722             goto toobig;
723         efree(evstr);
724     }
725     if (strlcat(line, LL_CMND_STR, len) >= len ||
726         strlcat(line, user_cmnd, len) >= len)
727         goto toobig;
728     if (user_args != NULL) {
729         if (strlcat(line, " ", len) >= len ||
730             strlcat(line, user_args, len) >= len)
731             goto toobig;
732     }
733
734     return (line);
735 toobig:
736     errorx(1, "internal error: insufficient space for log line");
737 }