1/*
2 * Copyright (c) 1994-1996, 1998-2012 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 <errno.h>
61#include <fcntl.h>
62
63#include "sudo.h"
64
65static void do_syslog		__P((int, char *));
66static void do_logfile		__P((char *));
67static void send_mail		__P((const char *fmt, ...));
68static int should_mail		__P((int));
69static void mysyslog		__P((int, const char *, ...));
70static char *new_logline	__P((const char *, int));
71
72extern char **NewArgv;	/* XXX - for auditing */
73
74#define MAXSYSLOGTRIES	16	/* num of retries for broken syslogs */
75
76/*
77 * We do an openlog(3)/closelog(3) for each message because some
78 * authentication methods (notably PAM) use syslog(3) for their
79 * own nefarious purposes and may call openlog(3) and closelog(3).
80 * Note that because we don't want to assume that all systems have
81 * vsyslog(3) (HP-UX doesn't) "%m" will not be expanded.
82 * Sadly this is a maze of #ifdefs.
83 */
84static void
85#ifdef __STDC__
86mysyslog(int pri, const char *fmt, ...)
87#else
88mysyslog(pri, fmt, va_alist)
89    int pri;
90    const char *fmt;
91    va_dcl
92#endif
93{
94#ifdef BROKEN_SYSLOG
95    int i;
96#endif
97    char buf[MAXSYSLOGLEN+1];
98    va_list ap;
99
100#ifdef __STDC__
101    va_start(ap, fmt);
102#else
103    va_start(ap);
104#endif
105#ifdef LOG_NFACILITIES
106    openlog("sudo", 0, def_syslog);
107#else
108    openlog("sudo", 0);
109#endif
110    vsnprintf(buf, sizeof(buf), fmt, ap);
111#ifdef BROKEN_SYSLOG
112    /*
113     * Some versions of syslog(3) don't guarantee success and return
114     * an int (notably HP-UX < 10.0).  So, if at first we don't succeed,
115     * try, try again...
116     */
117    for (i = 0; i < MAXSYSLOGTRIES; i++)
118	if (syslog(pri, "%s", buf) == 0)
119	    break;
120#else
121    syslog(pri, "%s", buf);
122#endif /* BROKEN_SYSLOG */
123    va_end(ap);
124    closelog();
125}
126
127#define FMT_FIRST "%8s : %s"
128#define FMT_CONTD "%8s : (command continued) %s"
129
130/*
131 * Log a message to syslog, pre-pending the username and splitting the
132 * message into parts if it is longer than MAXSYSLOGLEN.
133 */
134static void
135do_syslog(pri, msg)
136    int pri;
137    char *msg;
138{
139    size_t len, maxlen;
140    char *p, *tmp, save;
141    const char *fmt;
142
143#ifdef HAVE_SETLOCALE
144    const char *old_locale = estrdup(setlocale(LC_ALL, NULL));
145    if (!setlocale(LC_ALL, def_sudoers_locale))
146	setlocale(LC_ALL, "C");
147#endif /* HAVE_SETLOCALE */
148
149    /*
150     * Log the full line, breaking into multiple syslog(3) calls if necessary
151     */
152    fmt = FMT_FIRST;
153    maxlen = MAXSYSLOGLEN - (sizeof(FMT_FIRST) - 6 + strlen(user_name));
154    for (p = msg; *p != '\0'; ) {
155	len = strlen(p);
156	if (len > maxlen) {
157	    /*
158	     * Break up the line into what will fit on one syslog(3) line
159	     * Try to avoid breaking words into several lines if possible.
160	     */
161	    tmp = memrchr(p, ' ', maxlen);
162	    if (tmp == NULL)
163		tmp = p + maxlen;
164
165	    /* NULL terminate line, but save the char to restore later */
166	    save = *tmp;
167	    *tmp = '\0';
168
169	    mysyslog(pri, fmt, user_name, p);
170
171	    *tmp = save;			/* restore saved character */
172
173	    /* Advance p and eliminate leading whitespace */
174	    for (p = tmp; *p == ' '; p++)
175		;
176	} else {
177	    mysyslog(pri, fmt, user_name, p);
178	    p += len;
179	}
180	fmt = FMT_CONTD;
181	maxlen = MAXSYSLOGLEN - (sizeof(FMT_CONTD) - 6 + strlen(user_name));
182    }
183
184#ifdef HAVE_SETLOCALE
185    setlocale(LC_ALL, old_locale);
186    efree((void *)old_locale);
187#endif /* HAVE_SETLOCALE */
188}
189
190static void
191do_logfile(msg)
192    char *msg;
193{
194    char *full_line;
195    size_t len;
196    mode_t oldmask;
197    time_t now;
198    FILE *fp;
199
200    oldmask = umask(077);
201    fp = fopen(def_logfile, "a");
202    (void) umask(oldmask);
203    if (fp == NULL) {
204	send_mail("Can't open log file: %s: %s", def_logfile, strerror(errno));
205    } else if (!lock_file(fileno(fp), SUDO_LOCK)) {
206	send_mail("Can't lock log file: %s: %s", def_logfile, strerror(errno));
207    } else {
208#ifdef HAVE_SETLOCALE
209	const char *old_locale = estrdup(setlocale(LC_ALL, NULL));
210	if (!setlocale(LC_ALL, def_sudoers_locale))
211	    setlocale(LC_ALL, "C");
212#endif /* HAVE_SETLOCALE */
213
214	now = time(NULL);
215	if (def_loglinelen < sizeof(LOG_INDENT)) {
216	    /* Don't pretty-print long log file lines (hard to grep) */
217	    if (def_log_host)
218		(void) fprintf(fp, "%s : %s : HOST=%s : %s\n",
219		    get_timestr(now, def_log_year), user_name, user_shost, msg);
220	    else
221		(void) fprintf(fp, "%s : %s : %s\n",
222		    get_timestr(now, def_log_year), user_name, msg);
223	} else {
224	    if (def_log_host)
225		len = easprintf(&full_line, "%s : %s : HOST=%s : %s",
226		    get_timestr(now, def_log_year), user_name, user_shost, msg);
227	    else
228		len = easprintf(&full_line, "%s : %s : %s",
229		    get_timestr(now, def_log_year), user_name, msg);
230
231	    /*
232	     * Print out full_line with word wrap around def_loglinelen chars.
233	     */
234	    writeln_wrap(fp, full_line, len, def_loglinelen);
235	    efree(full_line);
236	}
237	(void) fflush(fp);
238	(void) lock_file(fileno(fp), SUDO_UNLOCK);
239	(void) fclose(fp);
240
241#ifdef HAVE_SETLOCALE
242	setlocale(LC_ALL, old_locale);
243	efree((void *)old_locale);
244#endif /* HAVE_SETLOCALE */
245    }
246}
247
248/*
249 * Log, audit and mail the denial message, optionally informing the user.
250 */
251void
252log_denial(status, inform_user)
253    int status;
254    int inform_user;
255{
256    char *message;
257    char *logline;
258
259    /* Handle auditing first. */
260    if (ISSET(status, FLAG_NO_USER | FLAG_NO_HOST))
261	audit_failure(NewArgv, "No user or host");
262    else
263	audit_failure(NewArgv, "validation failure");
264
265    /* Set error message. */
266    if (ISSET(status, FLAG_NO_USER))
267	message = "user NOT in sudoers";
268    else if (ISSET(status, FLAG_NO_HOST))
269	message = "user NOT authorized on host";
270    else
271	message = "command not allowed";
272
273    logline = new_logline(message, 0);
274
275    if (should_mail(status))
276	send_mail("%s", logline);	/* send mail based on status */
277
278    /* Inform the user if they failed to authenticate.  */
279    if (inform_user) {
280	if (ISSET(status, FLAG_NO_USER))
281	    (void) fprintf(stderr, "%s is not in the sudoers file.  %s",
282		user_name, "This incident will be reported.\n");
283	else if (ISSET(status, FLAG_NO_HOST))
284	    (void) fprintf(stderr, "%s is not allowed to run sudo on %s.  %s",
285		user_name, user_shost, "This incident will be reported.\n");
286	else if (ISSET(status, FLAG_NO_CHECK))
287	    (void) fprintf(stderr, "Sorry, user %s may not run sudo on %s.\n",
288		user_name, user_shost);
289	else
290	    (void) fprintf(stderr,
291		"Sorry, user %s is not allowed to execute '%s%s%s' as %s%s%s on %s.\n",
292		user_name, user_cmnd, user_args ? " " : "",
293		user_args ? user_args : "",
294		list_pw ? list_pw->pw_name : runas_pw ?
295		runas_pw->pw_name : user_name, runas_gr ? ":" : "",
296		runas_gr ? runas_gr->gr_name : "", user_host);
297    }
298
299    /*
300     * Log via syslog and/or a file.
301     */
302    if (def_syslog)
303	do_syslog(def_syslog_badpri, logline);
304    if (def_logfile)
305	do_logfile(logline);
306
307    efree(logline);
308}
309
310/*
311 * Log and audit that user was not allowed to run the command.
312 */
313void
314log_failure(status, flags)
315    int status;
316    int flags;
317{
318    int inform_user = TRUE;
319
320    /* The user doesn't always get to see the log message (path info). */
321    if (!ISSET(status, FLAG_NO_USER | FLAG_NO_HOST) && def_path_info &&
322	(flags == NOT_FOUND_DOT || flags == NOT_FOUND))
323	inform_user = FALSE;
324    log_denial(status, inform_user);
325
326    if (!inform_user) {
327	/*
328	 * We'd like to not leak path info at all here, but that can
329	 * *really* confuse the users.  To really close the leak we'd
330	 * have to say "not allowed to run foo" even when the problem
331	 * is just "no foo in path" since the user can trivially set
332	 * their path to just contain a single dir.
333	 */
334	if (flags == NOT_FOUND)
335	    warningx("%s: command not found", user_cmnd);
336	else if (flags == NOT_FOUND_DOT)
337	    warningx("ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run.", user_cmnd, user_cmnd, user_cmnd);
338    }
339}
340
341/*
342 * Log and audit that user was not able to authenticate themselves.
343 */
344void
345log_auth_failure(status, tries)
346    int status;
347    int tries;
348{
349    int flags = NO_MAIL;
350
351    /* Handle auditing first. */
352    audit_failure(NewArgv, "authentication failure");
353
354    /*
355     * Do we need to send mail?
356     * We want to avoid sending multiple messages for the same command
357     * so if we are going to send an email about the denial, that takes
358     * precedence.
359     */
360    if (ISSET(status, VALIDATE_OK)) {
361	/* Command allowed, auth failed; do we need to send mail? */
362	if (def_mail_badpass || def_mail_always)
363	    flags = 0;
364    } else {
365	/* Command denied, auth failed; make sure we don't send mail twice. */
366	if (def_mail_badpass && !should_mail(status))
367	    flags = 0;
368	/* Don't log the bad password message, we'll log a denial instead. */
369	flags |= NO_LOG;
370    }
371
372    /*
373     * If sudoers denied the command we'll log that separately.
374     */
375    if (ISSET(status, FLAG_BAD_PASSWORD)) {
376	log_error(flags, "%d incorrect password attempt%s",
377	    tries, tries == 1 ? "" : "s");
378    } else if (ISSET(status, FLAG_NON_INTERACTIVE)) {
379	log_error(flags, "a password is required");
380    }
381}
382
383/*
384 * Log and potentially mail the allowed command.
385 */
386void
387log_allowed(status)
388    int status;
389{
390    char *logline;
391
392    logline = new_logline(NULL, 0);
393
394    if (should_mail(status))
395	send_mail("%s", logline);	/* send mail based on status */
396
397    /*
398     * Log via syslog and/or a file.
399     */
400    if (def_syslog)
401	do_syslog(def_syslog_goodpri, logline);
402    if (def_logfile)
403	do_logfile(logline);
404
405    efree(logline);
406}
407
408/*
409 * Perform logging for log_error()/log_fatal()
410 */
411static void
412vlog_error(flags, fmt, ap)
413    int flags;
414    const char *fmt;
415    va_list ap;
416{
417    int serrno = errno;
418    char *message;
419    char *logline;
420
421    /* Become root if we are not already to avoid user interference */
422    set_perms(PERM_ROOT|PERM_NOEXIT);
423
424    /* Expand printf-style format + args. */
425    evasprintf(&message, fmt, ap);
426
427    if (ISSET(flags, MSG_ONLY))
428	logline = message;
429    else
430	logline = new_logline(message, ISSET(flags, USE_ERRNO) ? serrno : 0);
431
432    /*
433     * Tell the user.
434     */
435    if (!ISSET(flags, NO_STDERR)) {
436	if (ISSET(flags, USE_ERRNO))
437	    warning("%s", message);
438	else
439	    warningx("%s", message);
440    }
441    if (logline != message)
442        efree(message);
443
444    /*
445     * Send a copy of the error via mail.
446     */
447    if (!ISSET(flags, NO_MAIL))
448	send_mail("%s", logline);
449
450    /*
451     * Log to syslog and/or a file.
452     */
453    if (!ISSET(flags, NO_LOG)) {
454	if (def_syslog)
455	    do_syslog(def_syslog_badpri, logline);
456	if (def_logfile)
457	    do_logfile(logline);
458    }
459
460    efree(logline);
461}
462
463void
464#ifdef __STDC__
465log_error(int flags, const char *fmt, ...)
466#else
467log_error(flags, fmt, va_alist)
468    int flags;
469    const char *fmt;
470    va_dcl
471#endif
472{
473    va_list ap;
474
475    /* Log the error. */
476#ifdef __STDC__
477    va_start(ap, fmt);
478#else
479    va_start(ap);
480#endif
481    vlog_error(flags, fmt, ap);
482    va_end(ap);
483}
484
485void
486#ifdef __STDC__
487log_fatal(int flags, const char *fmt, ...)
488#else
489log_fatal(flags, fmt, va_alist)
490    int flags;
491    const char *fmt;
492    va_dcl
493#endif
494{
495    va_list ap;
496
497    /* Log the error. */
498#ifdef __STDC__
499    va_start(ap, fmt);
500#else
501    va_start(ap);
502#endif
503    vlog_error(flags, fmt, ap);
504    va_end(ap);
505
506    /* Clean up and exit. */
507    cleanup(0);
508    exit(1);
509}
510
511#define MAX_MAILFLAGS	63
512
513/*
514 * Send a message to MAILTO user
515 */
516static void
517#ifdef __STDC__
518send_mail(const char *fmt, ...)
519#else
520send_mail(fmt, va_alist)
521    const char *fmt;
522    va_dcl
523#endif
524{
525    FILE *mail;
526    char *p;
527    int fd, pfd[2], status;
528    pid_t pid, rv;
529    sigaction_t sa;
530    va_list ap;
531#ifndef NO_ROOT_MAILER
532    static char *root_envp[] = {
533	"HOME=/",
534	"PATH=/usr/bin:/bin:/usr/sbin:/sbin",
535	"LOGNAME=root",
536	"USERNAME=root",
537	"USER=root",
538	NULL
539    };
540#endif /* NO_ROOT_MAILER */
541
542    /* Just return if mailer is disabled. */
543    if (!def_mailerpath || !def_mailto)
544	return;
545
546    /* Fork and return, child will daemonize. */
547    switch (pid = fork()) {
548	case -1:
549	    /* Error. */
550	    error(1, "cannot fork");
551	    break;
552	case 0:
553	    /* Child. */
554	    switch (pid = fork()) {
555		case -1:
556		    /* Error. */
557		    mysyslog(LOG_ERR, "cannot fork: %m");
558		    _exit(1);
559		case 0:
560		    /* Grandchild continues below. */
561		    break;
562		default:
563		    /* Parent will wait for us. */
564		    _exit(0);
565	    }
566	    break;
567	default:
568	    /* Parent. */
569	    do {
570#ifdef HAVE_WAITPID
571		rv = waitpid(pid, &status, 0);
572#else
573		rv = wait(&status);
574#endif
575	    } while (rv == -1 && errno == EINTR);
576	    return;
577    }
578
579    /* Daemonize - disassociate from session/tty. */
580    if (setsid() == -1)
581      warning("setsid");
582    if (chdir("/") == -1)
583      warning("chdir(/)");
584    if ((fd = open(_PATH_DEVNULL, O_RDWR, 0644)) != -1) {
585	(void) dup2(fd, STDIN_FILENO);
586	(void) dup2(fd, STDOUT_FILENO);
587	(void) dup2(fd, STDERR_FILENO);
588    }
589
590#ifdef HAVE_SETLOCALE
591    if (!setlocale(LC_ALL, def_sudoers_locale)) {
592	setlocale(LC_ALL, "C");
593	efree(def_sudoers_locale);
594	def_sudoers_locale = estrdup("C");
595    }
596#endif /* HAVE_SETLOCALE */
597
598    /* Close password, group and other fds so we don't leak. */
599    sudo_endpwent();
600    sudo_endgrent();
601    closefrom(STDERR_FILENO + 1);
602
603    /* Ignore SIGPIPE in case mailer exits prematurely (or is missing). */
604    zero_bytes(&sa, sizeof(sa));
605    sigemptyset(&sa.sa_mask);
606    sa.sa_flags = SA_INTERRUPT;
607    sa.sa_handler = SIG_IGN;
608    (void) sigaction(SIGPIPE, &sa, NULL);
609
610    if (pipe(pfd) == -1) {
611	mysyslog(LOG_ERR, "cannot open pipe: %m");
612	_exit(1);
613    }
614
615    switch (pid = fork()) {
616	case -1:
617	    /* Error. */
618	    mysyslog(LOG_ERR, "cannot fork: %m");
619	    _exit(1);
620	    break;
621	case 0:
622	    {
623		char *argv[MAX_MAILFLAGS + 1];
624		char *mpath, *mflags;
625		int i;
626
627		/* Child, set stdin to output side of the pipe */
628		if (pfd[0] != STDIN_FILENO) {
629		    if (dup2(pfd[0], STDIN_FILENO) == -1) {
630			mysyslog(LOG_ERR, "cannot dup stdin: %m");
631			_exit(127);
632		    }
633		    (void) close(pfd[0]);
634		}
635		(void) close(pfd[1]);
636
637		/* Build up an argv based on the mailer path and flags */
638		mflags = estrdup(def_mailerflags);
639		mpath = estrdup(def_mailerpath);
640		if ((argv[0] = strrchr(mpath, ' ')))
641		    argv[0]++;
642		else
643		    argv[0] = mpath;
644
645		i = 1;
646		if ((p = strtok(mflags, " \t"))) {
647		    do {
648			argv[i] = p;
649		    } while (++i < MAX_MAILFLAGS && (p = strtok(NULL, " \t")));
650		}
651		argv[i] = NULL;
652
653		/*
654		 * Depending on the config, either run the mailer as root
655		 * (so user cannot kill it) or as the user (for the paranoid).
656		 */
657#ifndef NO_ROOT_MAILER
658		set_perms(PERM_ROOT|PERM_NOEXIT);
659		execve(mpath, argv, root_envp);
660#else
661		set_perms(PERM_FULL_USER|PERM_NOEXIT);
662		execv(mpath, argv);
663#endif /* NO_ROOT_MAILER */
664		mysyslog(LOG_ERR, "cannot execute %s: %m", mpath);
665		_exit(127);
666	    }
667	    break;
668    }
669
670    (void) close(pfd[0]);
671    mail = fdopen(pfd[1], "w");
672
673    /* Pipes are all setup, send message. */
674    (void) fprintf(mail, "To: %s\nFrom: %s\nAuto-Submitted: %s\nSubject: ",
675	def_mailto, def_mailfrom ? def_mailfrom : user_name, "auto-generated");
676    for (p = def_mailsub; *p; p++) {
677	/* Expand escapes in the subject */
678	if (*p == '%' && *(p+1) != '%') {
679	    switch (*(++p)) {
680		case 'h':
681		    (void) fputs(user_host, mail);
682		    break;
683		case 'u':
684		    (void) fputs(user_name, mail);
685		    break;
686		default:
687		    p--;
688		    break;
689	    }
690	} else
691	    (void) fputc(*p, mail);
692    }
693
694#ifdef HAVE_NL_LANGINFO
695    if (strcmp(def_sudoers_locale, "C") != 0)
696	(void) fprintf(mail, "\nContent-Type: text/plain; charset=\"%s\"\nContent-Transfer-Encoding: 8bit", nl_langinfo(CODESET));
697#endif /* HAVE_NL_LANGINFO */
698
699    (void) fprintf(mail, "\n\n%s : %s : %s : ", user_host,
700	get_timestr(time(NULL), def_log_year), user_name);
701#ifdef __STDC__
702    va_start(ap, fmt);
703#else
704    va_start(ap);
705#endif
706    (void) vfprintf(mail, fmt, ap);
707    va_end(ap);
708    fputs("\n\n", mail);
709
710    fclose(mail);
711    do {
712#ifdef HAVE_WAITPID
713        rv = waitpid(pid, &status, 0);
714#else
715        rv = wait(&status);
716#endif
717    } while (rv == -1 && errno == EINTR);
718    _exit(0);
719}
720
721/*
722 * Determine whether we should send mail based on "status" and defaults options.
723 */
724static int
725should_mail(status)
726    int status;
727{
728
729    return def_mail_always || ISSET(status, VALIDATE_ERROR) ||
730	(def_mail_no_user && ISSET(status, FLAG_NO_USER)) ||
731	(def_mail_no_host && ISSET(status, FLAG_NO_HOST)) ||
732	(def_mail_no_perms && !ISSET(status, VALIDATE_OK));
733}
734
735#define	LL_TTY_STR	"TTY="
736#define	LL_CWD_STR	"PWD="		/* XXX - should be CWD= */
737#define	LL_USER_STR	"USER="
738#define	LL_GROUP_STR	"GROUP="
739#define	LL_ENV_STR	"ENV="
740#define	LL_CMND_STR	"COMMAND="
741#define	LL_TSID_STR	"TSID="
742
743/*
744 * Allocate and fill in a new logline.
745 */
746static char *
747new_logline(message, serrno)
748    const char *message;
749    int serrno;
750{
751    size_t len = 0;
752    char *evstr = NULL;
753    char *errstr = NULL;
754    char *line;
755
756    /*
757     * Compute line length
758     */
759    if (message != NULL)
760	len += strlen(message) + 3;
761    if (serrno) {
762	errstr = strerror(serrno);
763	len += strlen(errstr) + 3;
764    }
765    len += sizeof(LL_TTY_STR) + 2 + strlen(user_tty);
766    len += sizeof(LL_CWD_STR) + 2 + strlen(user_cwd);
767    if (runas_pw != NULL)
768	len += sizeof(LL_USER_STR) + 2 + strlen(runas_pw->pw_name);
769    if (runas_gr != NULL)
770	len += sizeof(LL_GROUP_STR) + 2 + strlen(runas_gr->gr_name);
771    if (sudo_user.sessid[0] != '\0')
772	len += sizeof(LL_TSID_STR) + 2 + strlen(sudo_user.sessid);
773    if (sudo_user.env_vars != NULL) {
774	size_t evlen = 0;
775	struct list_member *cur;
776	for (cur = sudo_user.env_vars; cur != NULL; cur = cur->next)
777	    evlen += strlen(cur->value) + 1;
778	evstr = emalloc(evlen);
779	evstr[0] = '\0';
780	for (cur = sudo_user.env_vars; cur != NULL; cur = cur->next) {
781	    strlcat(evstr, cur->value, evlen);
782	    strlcat(evstr, " ", evlen);	/* NOTE: last one will fail */
783	}
784	len += sizeof(LL_ENV_STR) + 2 + evlen;
785    }
786    /* Note: we log "sudo -l command arg ..." as "list command arg ..." */
787    len += sizeof(LL_CMND_STR) - 1 + strlen(user_cmnd);
788    if (ISSET(sudo_mode, MODE_CHECK))
789	len += sizeof("list ") - 1;
790    if (user_args != NULL)
791	len += strlen(user_args) + 1;
792
793    /*
794     * Allocate and build up the line.
795     */
796    line = emalloc(++len);
797    line[0] = '\0';
798
799    if (message != NULL) {
800	if (strlcat(line, message, len) >= len ||
801	    strlcat(line, errstr ? " : " : " ; ", len) >= len)
802	    goto toobig;
803    }
804    if (serrno) {
805	if (strlcat(line, errstr, len) >= len ||
806	    strlcat(line, " ; ", len) >= len)
807	    goto toobig;
808    }
809    if (strlcat(line, LL_TTY_STR, len) >= len ||
810	strlcat(line, user_tty, len) >= len ||
811	strlcat(line, " ; ", len) >= len)
812	goto toobig;
813    if (strlcat(line, LL_CWD_STR, len) >= len ||
814	strlcat(line, user_cwd, len) >= len ||
815	strlcat(line, " ; ", len) >= len)
816	goto toobig;
817    if (runas_pw != NULL) {
818	if (strlcat(line, LL_USER_STR, len) >= len ||
819	    strlcat(line, runas_pw->pw_name, len) >= len ||
820	    strlcat(line, " ; ", len) >= len)
821	    goto toobig;
822    }
823    if (runas_gr != NULL) {
824	if (strlcat(line, LL_GROUP_STR, len) >= len ||
825	    strlcat(line, runas_gr->gr_name, len) >= len ||
826	    strlcat(line, " ; ", len) >= len)
827	    goto toobig;
828    }
829    if (sudo_user.sessid[0] != '\0') {
830	if (strlcat(line, LL_TSID_STR, len) >= len ||
831	    strlcat(line, sudo_user.sessid, len) >= len ||
832	    strlcat(line, " ; ", len) >= len)
833	    goto toobig;
834    }
835    if (evstr != NULL) {
836	if (strlcat(line, LL_ENV_STR, len) >= len ||
837	    strlcat(line, evstr, len) >= len ||
838	    strlcat(line, " ; ", len) >= len)
839	    goto toobig;
840	efree(evstr);
841    }
842    if (strlcat(line, LL_CMND_STR, len) >= len)
843	goto toobig;
844    if (ISSET(sudo_mode, MODE_CHECK) && strlcat(line, "list ", len) >= len)
845	goto toobig;
846    if (strlcat(line, user_cmnd, len) >= len)
847	goto toobig;
848    if (user_args != NULL) {
849	if (strlcat(line, " ", len) >= len ||
850	    strlcat(line, user_args, len) >= len)
851	    goto toobig;
852    }
853
854    return line;
855toobig:
856    errorx(1, "internal error: insufficient space for log line");
857}
858