395f83b41f8b517ed84eb5e885c0270e473686ec
[debian/sudo] / plugins / sudoers / logging.c
1 /*
2  * Copyright (c) 1994-1996, 1998-2011 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 #ifdef HAVE_SETLOCALE
51 # include <locale.h>
52 #endif /* HAVE_SETLOCALE */
53 #ifdef HAVE_NL_LANGINFO
54 # include <langinfo.h>
55 #endif /* HAVE_NL_LANGINFO */
56 #include <pwd.h>
57 #include <grp.h>
58 #include <signal.h>
59 #include <time.h>
60 #include <ctype.h>
61 #include <errno.h>
62 #include <fcntl.h>
63 #include <setjmp.h>
64
65 #include "sudoers.h"
66
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);
73
74 extern sigjmp_buf error_jmp;
75
76 #define MAXSYSLOGTRIES  16      /* num of retries for broken syslogs */
77
78 /*
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.
85  */
86 static void
87 mysyslog(int pri, const char *fmt, ...)
88 {
89 #ifdef BROKEN_SYSLOG
90     int i;
91 #endif
92     char buf[MAXSYSLOGLEN+1];
93     va_list ap;
94     debug_decl(mysyslog, SUDO_DEBUG_LOGGING)
95
96     va_start(ap, fmt);
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     debug_return;
118 }
119
120 #define FMT_FIRST "%8s : %s"
121 #define FMT_CONTD "%8s : (command continued) %s"
122
123 /*
124  * Log a message to syslog, pre-pending the username and splitting the
125  * message into parts if it is longer than MAXSYSLOGLEN.
126  */
127 static void
128 do_syslog(int pri, char *msg)
129 {
130     size_t len, maxlen;
131     char *p, *tmp, save;
132     const char *fmt;
133     debug_decl(do_syslog, SUDO_DEBUG_LOGGING)
134
135 #ifdef HAVE_SETLOCALE
136     const char *old_locale = estrdup(setlocale(LC_ALL, NULL));
137     if (!setlocale(LC_ALL, def_sudoers_locale))
138         setlocale(LC_ALL, "C");
139 #endif /* HAVE_SETLOCALE */
140
141     /*
142      * Log the full line, breaking into multiple syslog(3) calls if necessary
143      */
144     fmt = _(FMT_FIRST);
145     maxlen = MAXSYSLOGLEN - (strlen(fmt) - 5 + 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 - (strlen(fmt) - 5 + strlen(user_name));
174     }
175
176 #ifdef HAVE_SETLOCALE
177     setlocale(LC_ALL, old_locale);
178     efree((void *)old_locale);
179 #endif /* HAVE_SETLOCALE */
180
181     debug_return;
182 }
183
184 static void
185 do_logfile(char *msg)
186 {
187     char *full_line;
188     size_t len;
189     mode_t oldmask;
190     time_t now;
191     FILE *fp;
192     debug_decl(do_logfile, SUDO_DEBUG_LOGGING)
193
194     oldmask = umask(077);
195     fp = fopen(def_logfile, "a");
196     (void) umask(oldmask);
197     if (fp == NULL) {
198         send_mail(_("unable to open log file: %s: %s"),
199             def_logfile, strerror(errno));
200     } else if (!lock_file(fileno(fp), SUDO_LOCK)) {
201         send_mail(_("unable to lock log file: %s: %s"),
202             def_logfile, strerror(errno));
203     } else {
204 #ifdef HAVE_SETLOCALE
205         const char *old_locale = estrdup(setlocale(LC_ALL, NULL));
206         if (!setlocale(LC_ALL, def_sudoers_locale))
207             setlocale(LC_ALL, "C");
208 #endif /* HAVE_SETLOCALE */
209
210         now = time(NULL);
211         if (def_loglinelen < sizeof(LOG_INDENT)) {
212             /* Don't pretty-print long log file lines (hard to grep) */
213             if (def_log_host)
214                 (void) fprintf(fp, "%s : %s : HOST=%s : %s\n",
215                     get_timestr(now, def_log_year), user_name, user_shost, msg);
216             else
217                 (void) fprintf(fp, "%s : %s : %s\n",
218                     get_timestr(now, def_log_year), user_name, msg);
219         } else {
220             if (def_log_host)
221                 len = easprintf(&full_line, "%s : %s : HOST=%s : %s",
222                     get_timestr(now, def_log_year), user_name, user_shost, msg);
223             else
224                 len = easprintf(&full_line, "%s : %s : %s",
225                     get_timestr(now, def_log_year), user_name, msg);
226
227             /*
228              * Print out full_line with word wrap around def_loglinelen chars.
229              */
230             writeln_wrap(fp, full_line, len, def_loglinelen);
231             efree(full_line);
232         }
233         (void) fflush(fp);
234         (void) lock_file(fileno(fp), SUDO_UNLOCK);
235         (void) fclose(fp);
236
237 #ifdef HAVE_SETLOCALE
238         setlocale(LC_ALL, old_locale);
239         efree((void *)old_locale);
240 #endif /* HAVE_SETLOCALE */
241     }
242     debug_return;
243 }
244
245 /*
246  * Log and mail the denial message, optionally informing the user.
247  */
248 void
249 log_denial(int status, int inform_user)
250 {
251     char *logline, *message;
252     debug_decl(log_denial, SUDO_DEBUG_LOGGING)
253
254     /* Set error message. */
255     if (ISSET(status, FLAG_NO_USER))
256         message = _("user NOT in sudoers");
257     else if (ISSET(status, FLAG_NO_HOST))
258         message = _("user NOT authorized on host");
259     else
260         message = _("command not allowed");
261
262     logline = new_logline(message, 0);
263
264     if (should_mail(status))
265         send_mail("%s", logline);       /* send mail based on status */
266
267     /* Inform the user if they failed to authenticate.  */
268     if (inform_user) {
269         if (ISSET(status, FLAG_NO_USER)) {
270             sudo_printf(SUDO_CONV_ERROR_MSG, _("%s is not in the sudoers "
271                 "file.  This incident will be reported.\n"), user_name);
272         } else if (ISSET(status, FLAG_NO_HOST)) {
273             sudo_printf(SUDO_CONV_ERROR_MSG, _("%s is not allowed to run sudo "
274                 "on %s.  This incident will be reported.\n"),
275                 user_name, user_shost);
276         } else if (ISSET(status, FLAG_NO_CHECK)) {
277             sudo_printf(SUDO_CONV_ERROR_MSG, _("Sorry, user %s may not run "
278                 "sudo on %s.\n"), user_name, user_shost);
279         } else {
280             sudo_printf(SUDO_CONV_ERROR_MSG, _("Sorry, user %s is not allowed "
281                 "to execute '%s%s%s' as %s%s%s on %s.\n"),
282                 user_name, user_cmnd, user_args ? " " : "",
283                 user_args ? user_args : "",
284                 list_pw ? list_pw->pw_name : runas_pw ?
285                 runas_pw->pw_name : user_name, runas_gr ? ":" : "",
286                 runas_gr ? runas_gr->gr_name : "", user_host);
287         }
288     }
289
290     /*
291      * Log via syslog and/or a file.
292      */
293     if (def_syslog)
294         do_syslog(def_syslog_badpri, logline);
295     if (def_logfile)
296         do_logfile(logline);
297
298     efree(logline);
299     debug_return;
300 }
301
302 /*
303  * Log and potentially mail the allowed command.
304  */
305 void
306 log_allowed(int status)
307 {
308     char *logline;
309     debug_decl(log_allowed, SUDO_DEBUG_LOGGING)
310
311     logline = new_logline(NULL, 0);
312
313     if (should_mail(status))
314         send_mail("%s", logline);       /* send mail based on status */
315
316     /*
317      * Log via syslog and/or a file.
318      */
319     if (def_syslog)
320         do_syslog(def_syslog_goodpri, logline);
321     if (def_logfile)
322         do_logfile(logline);
323
324     efree(logline);
325     debug_return;
326 }
327
328 void
329 log_error(int flags, const char *fmt, ...)
330 {
331     int serrno = errno;
332     char *logline, *message;
333     va_list ap;
334     debug_decl(log_error, SUDO_DEBUG_LOGGING)
335
336     /* Expand printf-style format + args. */
337     va_start(ap, fmt);
338     evasprintf(&message, fmt, ap);
339     va_end(ap);
340
341     /* Become root if we are not already to avoid user interference */
342     set_perms(PERM_ROOT|PERM_NOEXIT);
343
344     if (ISSET(flags, MSG_ONLY))
345         logline = message;
346     else
347         logline = new_logline(message, ISSET(flags, USE_ERRNO) ? serrno : 0);
348
349     /*
350      * Tell the user.
351      */
352     if (!ISSET(flags, NO_STDERR)) {
353         if (ISSET(flags, USE_ERRNO))
354             warning("%s", message);
355         else
356             warningx("%s", message);
357     }
358     if (logline != message)
359         efree(message);
360
361     /*
362      * Send a copy of the error via mail.
363      */
364     if (!ISSET(flags, NO_MAIL))
365         send_mail("%s", logline);
366
367     /*
368      * Log to syslog and/or a file.
369      */
370     if (def_syslog)
371         do_syslog(def_syslog_badpri, logline);
372     if (def_logfile)
373         do_logfile(logline);
374
375     efree(logline);
376
377     restore_perms();
378
379     if (!ISSET(flags, NO_EXIT)) {
380         plugin_cleanup(0);
381         siglongjmp(error_jmp, 1);
382     }
383     debug_return;
384 }
385
386 #define MAX_MAILFLAGS   63
387
388 /*
389  * Send a message to MAILTO user
390  */
391 static void
392 send_mail(const char *fmt, ...)
393 {
394     FILE *mail;
395     char *p;
396     int fd, pfd[2], status;
397     pid_t pid, rv;
398     sigaction_t sa;
399     va_list ap;
400 #ifndef NO_ROOT_MAILER
401     static char *root_envp[] = {
402         "HOME=/",
403         "PATH=/usr/bin:/bin:/usr/sbin:/sbin",
404         "LOGNAME=root",
405         "USERNAME=root",
406         "USER=root",
407         NULL
408     };
409 #endif /* NO_ROOT_MAILER */
410     debug_decl(send_mail, SUDO_DEBUG_LOGGING)
411
412     /* Just return if mailer is disabled. */
413     if (!def_mailerpath || !def_mailto)
414         debug_return;
415
416     /* Fork and return, child will daemonize. */
417     switch (pid = fork()) {
418         case -1:
419             /* Error. */
420             error(1, _("unable to fork"));
421             break;
422         case 0:
423             /* Child. */
424             switch (pid = fork()) {
425                 case -1:
426                     /* Error. */
427                     mysyslog(LOG_ERR, _("unable to fork: %m"));
428                     sudo_debug_printf(SUDO_DEBUG_ERROR, "unable to fork: %s",
429                         strerror(errno));
430                     _exit(1);
431                 case 0:
432                     /* Grandchild continues below. */
433                     break;
434                 default:
435                     /* Parent will wait for us. */
436                     _exit(0);
437             }
438             break;
439         default:
440             /* Parent. */
441             do {
442                 rv = waitpid(pid, &status, 0);
443             } while (rv == -1 && errno == EINTR);
444             return; /* not debug */
445     }
446
447     /* Daemonize - disassociate from session/tty. */
448     if (setsid() == -1)
449       warning("setsid");
450     if (chdir("/") == -1)
451       warning("chdir(/)");
452     if ((fd = open(_PATH_DEVNULL, O_RDWR, 0644)) != -1) {
453         (void) dup2(fd, STDIN_FILENO);
454         (void) dup2(fd, STDOUT_FILENO);
455         (void) dup2(fd, STDERR_FILENO);
456     }
457
458 #ifdef HAVE_SETLOCALE
459     if (!setlocale(LC_ALL, def_sudoers_locale)) {
460         setlocale(LC_ALL, "C");
461         efree(def_sudoers_locale);
462         def_sudoers_locale = estrdup("C");
463     }
464 #endif /* HAVE_SETLOCALE */
465
466     /* Close password, group and other fds so we don't leak. */
467     sudo_endpwent();
468     sudo_endgrent();
469     closefrom(STDERR_FILENO + 1);
470
471     /* Ignore SIGPIPE in case mailer exits prematurely (or is missing). */
472     zero_bytes(&sa, sizeof(sa));
473     sigemptyset(&sa.sa_mask);
474     sa.sa_flags = SA_INTERRUPT;
475     sa.sa_handler = SIG_IGN;
476     (void) sigaction(SIGPIPE, &sa, NULL);
477
478     if (pipe(pfd) == -1) {
479         mysyslog(LOG_ERR, _("unable to open pipe: %m"));
480         sudo_debug_printf(SUDO_DEBUG_ERROR, "unable to open pipe: %s",
481             strerror(errno));
482         sudo_debug_exit(__func__, __FILE__, __LINE__, sudo_debug_subsys);
483         _exit(1);
484     }
485
486     switch (pid = fork()) {
487         case -1:
488             /* Error. */
489             mysyslog(LOG_ERR, _("unable to fork: %m"));
490             sudo_debug_printf(SUDO_DEBUG_ERROR, "unable to fork: %s",
491                 strerror(errno));
492             sudo_debug_exit(__func__, __FILE__, __LINE__, sudo_debug_subsys);
493             _exit(1);
494             break;
495         case 0:
496             {
497                 char *argv[MAX_MAILFLAGS + 1];
498                 char *mpath, *mflags;
499                 int i;
500
501                 /* Child, set stdin to output side of the pipe */
502                 if (pfd[0] != STDIN_FILENO) {
503                     if (dup2(pfd[0], STDIN_FILENO) == -1) {
504                         mysyslog(LOG_ERR, _("unable to dup stdin: %m"));
505                         sudo_debug_printf(SUDO_DEBUG_ERROR,
506                             "unable to dup stdin: %s", strerror(errno));
507                         _exit(127);
508                     }
509                     (void) close(pfd[0]);
510                 }
511                 (void) close(pfd[1]);
512
513                 /* Build up an argv based on the mailer path and flags */
514                 mflags = estrdup(def_mailerflags);
515                 mpath = estrdup(def_mailerpath);
516                 if ((argv[0] = strrchr(mpath, ' ')))
517                     argv[0]++;
518                 else
519                     argv[0] = mpath;
520
521                 i = 1;
522                 if ((p = strtok(mflags, " \t"))) {
523                     do {
524                         argv[i] = p;
525                     } while (++i < MAX_MAILFLAGS && (p = strtok(NULL, " \t")));
526                 }
527                 argv[i] = NULL;
528
529                 /*
530                  * Depending on the config, either run the mailer as root
531                  * (so user cannot kill it) or as the user (for the paranoid).
532                  */
533 #ifndef NO_ROOT_MAILER
534                 set_perms(PERM_ROOT|PERM_NOEXIT);
535                 execve(mpath, argv, root_envp);
536 #else
537                 set_perms(PERM_FULL_USER|PERM_NOEXIT);
538                 execv(mpath, argv);
539 #endif /* NO_ROOT_MAILER */
540                 mysyslog(LOG_ERR, _("unable to execute %s: %m"), mpath);
541                 sudo_debug_printf(SUDO_DEBUG_ERROR, "unable to execute %s: %s",
542                     mpath, strerror(errno));
543                 _exit(127);
544             }
545             break;
546     }
547
548     (void) close(pfd[0]);
549     mail = fdopen(pfd[1], "w");
550
551     /* Pipes are all setup, send message. */
552     (void) fprintf(mail, "To: %s\nFrom: %s\nAuto-Submitted: %s\nSubject: ",
553         def_mailto, def_mailfrom ? def_mailfrom : user_name, "auto-generated");
554     for (p = def_mailsub; *p; p++) {
555         /* Expand escapes in the subject */
556         if (*p == '%' && *(p+1) != '%') {
557             switch (*(++p)) {
558                 case 'h':
559                     (void) fputs(user_host, mail);
560                     break;
561                 case 'u':
562                     (void) fputs(user_name, mail);
563                     break;
564                 default:
565                     p--;
566                     break;
567             }
568         } else
569             (void) fputc(*p, mail);
570     }
571
572 #ifdef HAVE_NL_LANGINFO
573     if (strcmp(def_sudoers_locale, "C") != 0)
574         (void) fprintf(mail, "\nContent-Type: text/plain; charset=\"%s\"\nContent-Transfer-Encoding: 8bit", nl_langinfo(CODESET));
575 #endif /* HAVE_NL_LANGINFO */
576
577     (void) fprintf(mail, "\n\n%s : %s : %s : ", user_host,
578         get_timestr(time(NULL), def_log_year), user_name);
579     va_start(ap, fmt);
580     (void) vfprintf(mail, fmt, ap);
581     va_end(ap);
582     fputs("\n\n", mail);
583
584     fclose(mail);
585     do {
586         rv = waitpid(pid, &status, 0);
587     } while (rv == -1 && errno == EINTR);
588     sudo_debug_exit(__func__, __FILE__, __LINE__, sudo_debug_subsys);
589     _exit(0);
590 }
591
592 /*
593  * Determine whether we should send mail based on "status" and defaults options.
594  */
595 static int
596 should_mail(int status)
597 {
598     debug_decl(should_mail, SUDO_DEBUG_LOGGING)
599
600     debug_return_bool(def_mail_always || ISSET(status, VALIDATE_ERROR) ||
601         (def_mail_no_user && ISSET(status, FLAG_NO_USER)) ||
602         (def_mail_no_host && ISSET(status, FLAG_NO_HOST)) ||
603         (def_mail_no_perms && !ISSET(status, VALIDATE_OK)));
604 }
605
606 #define LL_TTY_STR      "TTY="
607 #define LL_CWD_STR      "PWD="          /* XXX - should be CWD= */
608 #define LL_USER_STR     "USER="
609 #define LL_GROUP_STR    "GROUP="
610 #define LL_ENV_STR      "ENV="
611 #define LL_CMND_STR     "COMMAND="
612 #define LL_TSID_STR     "TSID="
613
614 #define IS_SESSID(s) ( \
615     isalnum((unsigned char)(s)[0]) && isalnum((unsigned char)(s)[1]) && \
616     (s)[2] == '/' && \
617     isalnum((unsigned char)(s)[3]) && isalnum((unsigned char)(s)[4]) && \
618     (s)[5] == '/' && \
619     isalnum((unsigned char)(s)[6]) && isalnum((unsigned char)(s)[7]) && \
620     (s)[8] == '\0')
621
622 /*
623  * Allocate and fill in a new logline.
624  */
625 static char *
626 new_logline(const char *message, int serrno)
627 {
628     size_t len = 0;
629     char *errstr = NULL;
630     char *evstr = NULL;
631     char *line, sessid[7], *tsid = NULL;
632     debug_decl(new_logline, SUDO_DEBUG_LOGGING)
633
634     /* A TSID may be a sudoers-style session ID or a free-form string. */
635     if (sudo_user.iolog_file != NULL) {
636         if (IS_SESSID(sudo_user.iolog_file)) {
637             sessid[0] = sudo_user.iolog_file[0];
638             sessid[1] = sudo_user.iolog_file[1];
639             sessid[2] = sudo_user.iolog_file[3];
640             sessid[3] = sudo_user.iolog_file[4];
641             sessid[4] = sudo_user.iolog_file[6];
642             sessid[5] = sudo_user.iolog_file[7];
643             sessid[6] = '\0';
644             tsid = sessid;
645         } else {
646             tsid = sudo_user.iolog_file;
647         }
648     }
649
650     /*
651      * Compute line length
652      */
653     if (message != NULL)
654         len += strlen(message) + 3;
655     if (serrno) {
656         errstr = strerror(serrno);
657         len += strlen(errstr) + 3;
658     }
659     len += sizeof(LL_TTY_STR) + 2 + strlen(user_tty);
660     len += sizeof(LL_CWD_STR) + 2 + strlen(user_cwd);
661     if (runas_pw != NULL)
662         len += sizeof(LL_USER_STR) + 2 + strlen(runas_pw->pw_name);
663     if (runas_gr != NULL)
664         len += sizeof(LL_GROUP_STR) + 2 + strlen(runas_gr->gr_name);
665     if (tsid != NULL)
666         len += sizeof(LL_TSID_STR) + 2 + strlen(tsid);
667     if (sudo_user.env_vars != NULL) {
668         size_t evlen = 0;
669         char * const *ep;
670
671         for (ep = sudo_user.env_vars; *ep != NULL; ep++)
672             evlen += strlen(*ep) + 1;
673         evstr = emalloc(evlen);
674         evstr[0] = '\0';
675         for (ep = sudo_user.env_vars; *ep != NULL; ep++) {
676             strlcat(evstr, *ep, evlen);
677             strlcat(evstr, " ", evlen); /* NOTE: last one will fail */
678         }
679         len += sizeof(LL_ENV_STR) + 2 + evlen;
680     }
681     if (user_cmnd != NULL) {
682         /* Note: we log "sudo -l command arg ..." as "list command arg ..." */
683         len += sizeof(LL_CMND_STR) - 1 + strlen(user_cmnd);
684         if (ISSET(sudo_mode, MODE_CHECK))
685             len += sizeof("list ") - 1;
686         if (user_args != NULL)
687             len += strlen(user_args) + 1;
688     }
689
690     /*
691      * Allocate and build up the line.
692      */
693     line = emalloc(++len);
694     line[0] = '\0';
695
696     if (message != NULL) {
697         if (strlcat(line, message, len) >= len ||
698             strlcat(line, errstr ? " : " : " ; ", len) >= len)
699             goto toobig;
700     }
701     if (serrno) {
702         if (strlcat(line, errstr, len) >= len ||
703             strlcat(line, " ; ", len) >= len)
704             goto toobig;
705     }
706     if (strlcat(line, LL_TTY_STR, len) >= len ||
707         strlcat(line, user_tty, len) >= len ||
708         strlcat(line, " ; ", len) >= len)
709         goto toobig;
710     if (strlcat(line, LL_CWD_STR, len) >= len ||
711         strlcat(line, user_cwd, len) >= len ||
712         strlcat(line, " ; ", len) >= len)
713         goto toobig;
714     if (runas_pw != NULL) {
715         if (strlcat(line, LL_USER_STR, len) >= len ||
716             strlcat(line, runas_pw->pw_name, len) >= len ||
717             strlcat(line, " ; ", len) >= len)
718             goto toobig;
719     }
720     if (runas_gr != NULL) {
721         if (strlcat(line, LL_GROUP_STR, len) >= len ||
722             strlcat(line, runas_gr->gr_name, len) >= len ||
723             strlcat(line, " ; ", len) >= len)
724             goto toobig;
725     }
726     if (tsid != NULL) {
727         if (strlcat(line, LL_TSID_STR, len) >= len ||
728             strlcat(line, tsid, len) >= len ||
729             strlcat(line, " ; ", len) >= len)
730             goto toobig;
731     }
732     if (evstr != NULL) {
733         if (strlcat(line, LL_ENV_STR, len) >= len ||
734             strlcat(line, evstr, len) >= len ||
735             strlcat(line, " ; ", len) >= len)
736             goto toobig;
737         efree(evstr);
738     }
739     if (user_cmnd != NULL) {
740         if (strlcat(line, LL_CMND_STR, len) >= len)
741             goto toobig;
742         if (ISSET(sudo_mode, MODE_CHECK) && strlcat(line, "list ", len) >= len)
743             goto toobig;
744         if (strlcat(line, user_cmnd, len) >= len)
745             goto toobig;
746         if (user_args != NULL) {
747             if (strlcat(line, " ", len) >= len ||
748                 strlcat(line, user_args, len) >= len)
749                 goto toobig;
750         }
751     }
752
753     debug_return_str(line);
754 toobig:
755     errorx(1, _("internal error: insufficient space for log line"));
756 }