Imported Upstream version 1.8.1p2
[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
95     va_start(ap, fmt);
96 #ifdef LOG_NFACILITIES
97     openlog("sudo", 0, def_syslog);
98 #else
99     openlog("sudo", 0);
100 #endif
101     vsnprintf(buf, sizeof(buf), fmt, ap);
102 #ifdef BROKEN_SYSLOG
103     /*
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,
106      * try, try again...
107      */
108     for (i = 0; i < MAXSYSLOGTRIES; i++)
109         if (syslog(pri, "%s", buf) == 0)
110             break;
111 #else
112     syslog(pri, "%s", buf);
113 #endif /* BROKEN_SYSLOG */
114     va_end(ap);
115     closelog();
116 }
117
118 #define FMT_FIRST "%8s : %s"
119 #define FMT_CONTD "%8s : (command continued) %s"
120
121 /*
122  * Log a message to syslog, pre-pending the username and splitting the
123  * message into parts if it is longer than MAXSYSLOGLEN.
124  */
125 static void
126 do_syslog(int pri, char *msg)
127 {
128     size_t len, maxlen;
129     char *p, *tmp, save;
130     const char *fmt;
131
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 */
137
138     /*
139      * Log the full line, breaking into multiple syslog(3) calls if necessary
140      */
141     fmt = FMT_FIRST;
142     maxlen = MAXSYSLOGLEN - (sizeof(FMT_FIRST) - 6 + strlen(user_name));
143     for (p = msg; *p != '\0'; ) {
144         len = strlen(p);
145         if (len > maxlen) {
146             /*
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.
149              */
150             tmp = memrchr(p, ' ', maxlen);
151             if (tmp == NULL)
152                 tmp = p + maxlen;
153
154             /* NULL terminate line, but save the char to restore later */
155             save = *tmp;
156             *tmp = '\0';
157
158             mysyslog(pri, fmt, user_name, p);
159
160             *tmp = save;                        /* restore saved character */
161
162             /* Advance p and eliminate leading whitespace */
163             for (p = tmp; *p == ' '; p++)
164                 ;
165         } else {
166             mysyslog(pri, fmt, user_name, p);
167             p += len;
168         }
169         fmt = FMT_CONTD;
170         maxlen = MAXSYSLOGLEN - (sizeof(FMT_CONTD) - 6 + strlen(user_name));
171     }
172
173 #ifdef HAVE_SETLOCALE
174     setlocale(LC_ALL, old_locale);
175     efree((void *)old_locale);
176 #endif /* HAVE_SETLOCALE */
177 }
178
179 static void
180 do_logfile(char *msg)
181 {
182     char *full_line;
183     char *beg, *oldend, *end;
184     FILE *fp;
185     mode_t oldmask;
186     size_t maxlen;
187
188     oldmask = umask(077);
189     maxlen = def_loglinelen > 0 ? def_loglinelen : 0;
190     fp = fopen(def_logfile, "a");
191     (void) umask(oldmask);
192     if (fp == NULL) {
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));
196     } else {
197         time_t now;
198
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 */
204
205         now = time(NULL);
206         if (def_loglinelen == 0) {
207             /* Don't pretty-print long log file lines (hard to grep) */
208             if (def_log_host)
209                 (void) fprintf(fp, "%s : %s : HOST=%s : %s\n",
210                     get_timestr(now, def_log_year), user_name, user_shost, msg);
211             else
212                 (void) fprintf(fp, "%s : %s : %s\n",
213                     get_timestr(now, def_log_year), user_name, msg);
214         } else {
215             if (def_log_host)
216                 easprintf(&full_line, "%s : %s : HOST=%s : %s",
217                     get_timestr(now, def_log_year), user_name, user_shost, msg);
218             else
219                 easprintf(&full_line, "%s : %s : %s",
220                     get_timestr(now, def_log_year), user_name, msg);
221
222             /*
223              * Print out full_line with word wrap
224              */
225             beg = end = full_line;
226             while (beg) {
227                 oldend = end;
228                 end = strchr(oldend, ' ');
229
230                 if (maxlen > 0 && end) {
231                     *end = '\0';
232                     if (strlen(beg) > maxlen) {
233                         /* too far, need to back up & print the line */
234
235                         if (beg == (char *)full_line)
236                             maxlen -= 4;        /* don't indent first line */
237
238                         *end = ' ';
239                         if (oldend != beg) {
240                             /* rewind & print */
241                             end = oldend-1;
242                             while (*end == ' ')
243                                 --end;
244                             *(++end) = '\0';
245                             (void) fprintf(fp, "%s\n    ", beg);
246                             *end = ' ';
247                         } else {
248                             (void) fprintf(fp, "%s\n    ", beg);
249                         }
250
251                         /* reset beg to point to the start of the new substr */
252                         beg = end;
253                         while (*beg == ' ')
254                             ++beg;
255                     } else {
256                         /* we still have room */
257                         *end = ' ';
258                     }
259
260                     /* remove leading whitespace */
261                     while (*end == ' ')
262                         ++end;
263                 } else {
264                     /* final line */
265                     (void) fprintf(fp, "%s\n", beg);
266                     beg = NULL;                 /* exit condition */
267                 }
268             }
269             efree(full_line);
270         }
271         (void) fflush(fp);
272         (void) lock_file(fileno(fp), SUDO_UNLOCK);
273         (void) fclose(fp);
274
275 #ifdef HAVE_SETLOCALE
276         setlocale(LC_ALL, old_locale);
277         efree((void *)old_locale);
278 #endif /* HAVE_SETLOCALE */
279     }
280 }
281
282 /*
283  * Log and mail the denial message, optionally informing the user.
284  */
285 void
286 log_denial(int status, int inform_user)
287 {
288     char *message;
289     char *logline;
290
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";
296     else
297         message = "command not allowed";
298
299     logline = new_logline(message, 0);
300
301     if (should_mail(status))
302         send_mail("%s", logline);       /* send mail based on status */
303
304     /* Inform the user if they failed to authenticate.  */
305     if (inform_user) {
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);
316         } else {
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);
324         }
325     }
326
327     /*
328      * Log via syslog and/or a file.
329      */
330     if (def_syslog)
331         do_syslog(def_syslog_badpri, logline);
332     if (def_logfile)
333         do_logfile(logline);
334
335     efree(logline);
336 }
337
338 /*
339  * Log and potentially mail the allowed command.
340  */
341 void
342 log_allowed(int status)
343 {
344     char *logline;
345
346     logline = new_logline(NULL, 0);
347
348     if (should_mail(status))
349         send_mail("%s", logline);       /* send mail based on status */
350
351     /*
352      * Log via syslog and/or a file.
353      */
354     if (def_syslog)
355         do_syslog(def_syslog_goodpri, logline);
356     if (def_logfile)
357         do_logfile(logline);
358
359     efree(logline);
360 }
361
362 void
363 log_error(int flags, const char *fmt, ...)
364 {
365     int serrno = errno;
366     char *message;
367     char *logline;
368     va_list ap;
369
370     /* Expand printf-style format + args. */
371     va_start(ap, fmt);
372     evasprintf(&message, fmt, ap);
373     va_end(ap);
374
375     /* Become root if we are not already to avoid user interference */
376     set_perms(PERM_ROOT|PERM_NOEXIT);
377
378     if (ISSET(flags, MSG_ONLY))
379         logline = message;
380     else
381         logline = new_logline(message, ISSET(flags, USE_ERRNO) ? serrno : 0);
382
383     /*
384      * Tell the user.
385      */
386     if (!ISSET(flags, NO_STDERR)) {
387         if (ISSET(flags, USE_ERRNO))
388             warning("%s", message);
389         else
390             warningx("%s", message);
391     }
392     if (logline != message)
393         efree(message);
394
395     /*
396      * Send a copy of the error via mail.
397      */
398     if (!ISSET(flags, NO_MAIL))
399         send_mail("%s", logline);
400
401     /*
402      * Log to syslog and/or a file.
403      */
404     if (def_syslog)
405         do_syslog(def_syslog_badpri, logline);
406     if (def_logfile)
407         do_logfile(logline);
408
409     efree(logline);
410
411     restore_perms();
412
413     if (!ISSET(flags, NO_EXIT)) {
414         plugin_cleanup(0);
415         siglongjmp(error_jmp, 1);
416     }
417 }
418
419 #define MAX_MAILFLAGS   63
420
421 /*
422  * Send a message to MAILTO user
423  */
424 static void
425 send_mail(const char *fmt, ...)
426 {
427     FILE *mail;
428     char *p;
429     int fd, pfd[2], status;
430     pid_t pid, rv;
431     sigaction_t sa;
432     va_list ap;
433 #ifndef NO_ROOT_MAILER
434     static char *root_envp[] = {
435         "HOME=/",
436         "PATH=/usr/bin:/bin:/usr/sbin:/sbin",
437         "LOGNAME=root",
438         "USERNAME=root",
439         "USER=root",
440         NULL
441     };
442 #endif /* NO_ROOT_MAILER */
443
444     /* Just return if mailer is disabled. */
445     if (!def_mailerpath || !def_mailto)
446         return;
447
448     /* Fork and return, child will daemonize. */
449     switch (pid = fork()) {
450         case -1:
451             /* Error. */
452             error(1, "cannot fork");
453             break;
454         case 0:
455             /* Child. */
456             switch (pid = fork()) {
457                 case -1:
458                     /* Error. */
459                     mysyslog(LOG_ERR, "cannot fork: %m");
460                     _exit(1);
461                 case 0:
462                     /* Grandchild continues below. */
463                     break;
464                 default:
465                     /* Parent will wait for us. */
466                     _exit(0);
467             }
468             break;
469         default:
470             /* Parent. */
471             do {
472                 rv = waitpid(pid, &status, 0);
473             } while (rv == -1 && errno == EINTR);
474             return;
475     }
476
477     /* Daemonize - disassociate from session/tty. */
478     if (setsid() == -1)
479       warning("setsid");
480     if (chdir("/") == -1)
481       warning("chdir(/)");
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);
486     }
487
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");
493     }
494 #endif /* HAVE_SETLOCALE */
495
496     /* Close password, group and other fds so we don't leak. */
497     sudo_endpwent();
498     sudo_endgrent();
499     closefrom(STDERR_FILENO + 1);
500
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);
507
508     if (pipe(pfd) == -1) {
509         mysyslog(LOG_ERR, "cannot open pipe: %m");
510         _exit(1);
511     }
512
513     switch (pid = fork()) {
514         case -1:
515             /* Error. */
516             mysyslog(LOG_ERR, "cannot fork: %m");
517             _exit(1);
518             break;
519         case 0:
520             {
521                 char *argv[MAX_MAILFLAGS + 1];
522                 char *mpath, *mflags;
523                 int i;
524
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");
529                         _exit(127);
530                     }
531                     (void) close(pfd[0]);
532                 }
533                 (void) close(pfd[1]);
534
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, ' ')))
539                     argv[0]++;
540                 else
541                     argv[0] = mpath;
542
543                 i = 1;
544                 if ((p = strtok(mflags, " \t"))) {
545                     do {
546                         argv[i] = p;
547                     } while (++i < MAX_MAILFLAGS && (p = strtok(NULL, " \t")));
548                 }
549                 argv[i] = NULL;
550
551                 /*
552                  * Depending on the config, either run the mailer as root
553                  * (so user cannot kill it) or as the user (for the paranoid).
554                  */
555 #ifndef NO_ROOT_MAILER
556                 set_perms(PERM_ROOT|PERM_NOEXIT);
557                 execve(mpath, argv, root_envp);
558 #else
559                 set_perms(PERM_FULL_USER|PERM_NOEXIT);
560                 execv(mpath, argv);
561 #endif /* NO_ROOT_MAILER */
562                 mysyslog(LOG_ERR, "cannot execute %s: %m", mpath);
563                 _exit(127);
564             }
565             break;
566     }
567
568     (void) close(pfd[0]);
569     mail = fdopen(pfd[1], "w");
570
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) != '%') {
577             switch (*(++p)) {
578                 case 'h':
579                     (void) fputs(user_host, mail);
580                     break;
581                 case 'u':
582                     (void) fputs(user_name, mail);
583                     break;
584                 default:
585                     p--;
586                     break;
587             }
588         } else
589             (void) fputc(*p, mail);
590     }
591
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 */
596
597     (void) fprintf(mail, "\n\n%s : %s : %s : ", user_host,
598         get_timestr(time(NULL), def_log_year), user_name);
599     va_start(ap, fmt);
600     (void) vfprintf(mail, fmt, ap);
601     va_end(ap);
602     fputs("\n\n", mail);
603
604     fclose(mail);
605     do {
606         rv = waitpid(pid, &status, 0);
607     } while (rv == -1 && errno == EINTR);
608     _exit(0);
609 }
610
611 /*
612  * Determine whether we should send mail based on "status" and defaults options.
613  */
614 static int
615 should_mail(int status)
616 {
617
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));
622 }
623
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="
631
632 #define IS_SESSID(s) ( \
633     isalnum((unsigned char)(s)[0]) && isalnum((unsigned char)(s)[1]) && \
634     (s)[2] == '/' && \
635     isalnum((unsigned char)(s)[3]) && isalnum((unsigned char)(s)[4]) && \
636     (s)[5] == '/' && \
637     isalnum((unsigned char)(s)[6]) && isalnum((unsigned char)(s)[7]) && \
638     (s)[8] == '\0')
639
640 /*
641  * Allocate and fill in a new logline.
642  */
643 static char *
644 new_logline(const char *message, int serrno)
645 {
646     size_t len = 0;
647     char *errstr = NULL;
648     char *evstr = NULL;
649     char *line, sessid[7], *tsid = NULL;
650
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];
660             sessid[6] = '\0';
661             tsid = sessid;
662         } else {
663             tsid = sudo_user.iolog_file;
664         }
665     }
666
667     /*
668      * Compute line length
669      */
670     if (message != NULL)
671         len += strlen(message) + 3;
672     if (serrno) {
673         errstr = strerror(serrno);
674         len += strlen(errstr) + 3;
675     }
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);
682     if (tsid != NULL)
683         len += sizeof(LL_TSID_STR) + 2 + strlen(tsid);
684     if (sudo_user.env_vars != NULL) {
685         size_t evlen = 0;
686         char * const *ep;
687
688         for (ep = sudo_user.env_vars; *ep != NULL; ep++)
689             evlen += strlen(*ep) + 1;
690         evstr = emalloc(evlen);
691         evstr[0] = '\0';
692         for (ep = sudo_user.env_vars; *ep != NULL; ep++) {
693             strlcat(evstr, *ep, evlen);
694             strlcat(evstr, " ", evlen); /* NOTE: last one will fail */
695         }
696         len += sizeof(LL_ENV_STR) + 2 + evlen;
697     }
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;
705     }
706
707     /*
708      * Allocate and build up the line.
709      */
710     line = emalloc(++len);
711     line[0] = '\0';
712
713     if (message != NULL) {
714         if (strlcat(line, message, len) >= len ||
715             strlcat(line, errstr ? " : " : " ; ", len) >= len)
716             goto toobig;
717     }
718     if (serrno) {
719         if (strlcat(line, errstr, len) >= len ||
720             strlcat(line, " ; ", len) >= len)
721             goto toobig;
722     }
723     if (strlcat(line, LL_TTY_STR, len) >= len ||
724         strlcat(line, user_tty, len) >= len ||
725         strlcat(line, " ; ", len) >= len)
726         goto toobig;
727     if (strlcat(line, LL_CWD_STR, len) >= len ||
728         strlcat(line, user_cwd, len) >= len ||
729         strlcat(line, " ; ", len) >= len)
730         goto toobig;
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)
735             goto toobig;
736     }
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)
741             goto toobig;
742     }
743     if (tsid != NULL) {
744         if (strlcat(line, LL_TSID_STR, len) >= len ||
745             strlcat(line, tsid, len) >= len ||
746             strlcat(line, " ; ", len) >= len)
747             goto toobig;
748     }
749     if (evstr != NULL) {
750         if (strlcat(line, LL_ENV_STR, len) >= len ||
751             strlcat(line, evstr, len) >= len ||
752             strlcat(line, " ; ", len) >= len)
753             goto toobig;
754         efree(evstr);
755     }
756     if (user_cmnd != NULL) {
757         if (strlcat(line, LL_CMND_STR, len) >= len)
758             goto toobig;
759         if (ISSET(sudo_mode, MODE_CHECK) && strlcat(line, "list ", len) >= len)
760             goto toobig;
761         if (strlcat(line, user_cmnd, len) >= len)
762             goto toobig;
763         if (user_args != NULL) {
764             if (strlcat(line, " ", len) >= len ||
765                 strlcat(line, user_args, len) >= len)
766                 goto toobig;
767         }
768     }
769
770     return line;
771 toobig:
772     errorx(1, "internal error: insufficient space for log line");
773 }