pull in stable security update 1.6.9p17-2+lenny1
[debian/sudo] / sudo.c
1 /*
2  * Copyright (c) 1993-1996,1998-2007 Todd C. Miller <Todd.Miller@courtesan.com>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  *
16  * Sponsored in part by the Defense Advanced Research Projects
17  * Agency (DARPA) and Air Force Research Laboratory, Air Force
18  * Materiel Command, USAF, under agreement number F39502-99-1-0512.
19  *
20  * For a brief history of sudo, please see the HISTORY file included
21  * with this distribution.
22  */
23
24 #define _SUDO_MAIN
25
26 #ifdef __TANDEM
27 # include <floss.h>
28 #endif
29
30 #include <config.h>
31
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <sys/param.h>
35 #include <sys/socket.h>
36 #ifdef HAVE_SETRLIMIT
37 # include <sys/time.h>
38 # include <sys/resource.h>
39 #endif
40 #include <stdio.h>
41 #ifdef STDC_HEADERS
42 # include <stdlib.h>
43 # include <stddef.h>
44 #else
45 # ifdef HAVE_STDLIB_H
46 #  include <stdlib.h>
47 # endif
48 #endif /* STDC_HEADERS */
49 #ifdef HAVE_STRING_H
50 # if defined(HAVE_MEMORY_H) && !defined(STDC_HEADERS)
51 #  include <memory.h>
52 # endif
53 # include <string.h>
54 #else
55 # ifdef HAVE_STRINGS_H
56 #  include <strings.h>
57 # endif
58 #endif /* HAVE_STRING_H */
59 #ifdef HAVE_UNISTD_H
60 # include <unistd.h>
61 #endif /* HAVE_UNISTD_H */
62 #ifdef HAVE_ERR_H
63 # include <err.h>
64 #else
65 # include "emul/err.h"
66 #endif /* HAVE_ERR_H */
67 #include <pwd.h>
68 #include <errno.h>
69 #include <fcntl.h>
70 #include <signal.h>
71 #include <grp.h>
72 #if TIME_WITH_SYS_TIME
73 # include <time.h>
74 #endif
75 #ifdef HAVE_SETLOCALE
76 # include <locale.h>
77 #endif
78 #include <netinet/in.h>
79 #include <netdb.h>
80 #if defined(HAVE_GETPRPWNAM) && defined(HAVE_SET_AUTH_PARAMETERS)
81 # ifdef __hpux
82 #  undef MAXINT
83 #  include <hpsecurity.h>
84 # else
85 #  include <sys/security.h>
86 # endif /* __hpux */
87 # include <prot.h>
88 #endif /* HAVE_GETPRPWNAM && HAVE_SET_AUTH_PARAMETERS */
89 #ifdef HAVE_LOGIN_CAP_H
90 # include <login_cap.h>
91 # ifndef LOGIN_DEFROOTCLASS
92 #  define LOGIN_DEFROOTCLASS    "daemon"
93 # endif
94 #endif
95 #ifdef HAVE_PROJECT_H
96 # include <project.h>
97 # include <sys/task.h>
98 #endif
99 #ifdef HAVE_SELINUX
100 # include <selinux/selinux.h>
101 #endif
102
103 #include "sudo.h"
104 #include "interfaces.h"
105 #include "version.h"
106
107 #ifndef lint
108 __unused __unused static const char rcsid[] = "$Sudo: sudo.c,v 1.369.2.41 2008/06/21 19:04:07 millert Exp $";
109 #endif /* lint */
110
111 /*
112  * Prototypes
113  */
114 static int init_vars                    __P((int, char **));
115 static int parse_args                   __P((int, char **));
116 static void check_sudoers               __P((void));
117 static void initial_setup               __P((void));
118 static void set_loginclass              __P((struct passwd *));
119 static void set_project                 __P((struct passwd *));
120 static void usage                       __P((int))
121                                             __attribute__((__noreturn__));
122 static void usage_excl                  __P((int))
123                                             __attribute__((__noreturn__));
124 static void usage_excl                  __P((int));
125 static struct passwd *get_authpw        __P((void));
126 extern int sudo_edit                    __P((int, char **, char **));
127 extern void list_matches                __P((void));
128 extern char **rebuild_env               __P((char **, int, int));
129 extern void validate_env_vars           __P((struct list_member *));
130 extern char **insert_env_vars           __P((char **, struct list_member *));
131 extern struct passwd *sudo_getpwnam     __P((const char *));
132 extern struct passwd *sudo_getpwuid     __P((uid_t));
133 extern struct passwd *sudo_pwdup        __P((const struct passwd *));
134 extern void runas_resetgroups           __P((void));
135
136 /*
137  * Globals
138  */
139 int Argc, NewArgc;
140 char **Argv, **NewArgv;
141 char *prev_user;
142 struct sudo_user sudo_user;
143 struct passwd *auth_pw;
144 FILE *sudoers_fp;
145 struct interface *interfaces;
146 int num_interfaces;
147 int tgetpass_flags;
148 uid_t timestamp_uid;
149 extern int errorlineno;
150 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
151 static struct rlimit corelimit;
152 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
153 #ifdef HAVE_LOGIN_CAP_H
154 login_cap_t *lc;
155 #endif /* HAVE_LOGIN_CAP_H */
156 #ifdef HAVE_BSD_AUTH_H
157 char *login_style;
158 #endif /* HAVE_BSD_AUTH_H */
159 sigaction_t saved_sa_int, saved_sa_quit, saved_sa_tstp;
160
161
162 int
163 main(argc, argv, envp)
164     int argc;
165     char **argv;
166     char **envp;
167 {
168     int validated;
169     int fd;
170     int cmnd_status;
171     int sudo_mode;
172     int pwflag;
173     sigaction_t sa;
174     extern int printmatches;
175     extern char **environ;
176
177 #ifdef HAVE_SETLOCALE
178     setlocale(LC_ALL, "");
179 #endif
180
181     Argv = argv;
182     if ((Argc = argc) < 1)
183         usage(1);
184
185     /* Must be done as the first thing... */
186 #if defined(HAVE_GETPRPWNAM) && defined(HAVE_SET_AUTH_PARAMETERS)
187     (void) set_auth_parameters(Argc, Argv);
188 # ifdef HAVE_INITPRIVS
189     initprivs();
190 # endif
191 #endif /* HAVE_GETPRPWNAM && HAVE_SET_AUTH_PARAMETERS */
192
193     if (geteuid() != 0)
194         errx(1, "must be setuid root");
195
196     /*
197      * Signal setup:
198      *  Ignore keyboard-generated signals so the user cannot interrupt
199      *  us at some point and avoid the logging.
200      *  Install handler to wait for children when they exit.
201      */
202     sigemptyset(&sa.sa_mask);
203     sa.sa_flags = SA_RESTART;
204     sa.sa_handler = SIG_IGN;
205     (void) sigaction(SIGINT, &sa, &saved_sa_int);
206     (void) sigaction(SIGQUIT, &sa, &saved_sa_quit);
207     (void) sigaction(SIGTSTP, &sa, &saved_sa_tstp);
208
209     /*
210      * Turn off core dumps and close open files.
211      */
212     initial_setup();
213     setpwent();
214
215     /* Parse our arguments. */
216     sudo_mode = parse_args(Argc, Argv);
217
218     /* Setup defaults data structures. */
219     init_defaults();
220
221     /* Load the list of local ip addresses and netmasks.  */
222     load_interfaces();
223
224     pwflag = 0;
225     if (ISSET(sudo_mode, MODE_SHELL))
226         user_cmnd = "shell";
227     else if (ISSET(sudo_mode, MODE_EDIT))
228         user_cmnd = "sudoedit";
229     else
230         switch (sudo_mode) {
231             case MODE_VERSION:
232                 (void) printf("Sudo version %s\n", version);
233                 if (getuid() == 0) {
234                     putchar('\n');
235                     (void) printf("Sudoers path: %s\n", _PATH_SUDOERS);
236                     dump_auth_methods();
237                     dump_defaults();
238                     dump_interfaces();
239                 }
240                 exit(0);
241                 break;
242             case MODE_HELP:
243                 usage(0);
244                 break;
245             case MODE_VALIDATE:
246                 user_cmnd = "validate";
247                 pwflag = I_VERIFYPW;
248                 break;
249             case MODE_KILL:
250             case MODE_INVALIDATE:
251                 user_cmnd = "kill";
252                 pwflag = -1;
253                 break;
254             case MODE_LISTDEFS:
255                 list_options();
256                 exit(0);
257                 break;
258             case MODE_LIST:
259                 user_cmnd = "list";
260                 pwflag = I_LISTPW;
261                 printmatches = 1;
262                 break;
263         }
264
265     /* Must have a command to run... */
266     if (user_cmnd == NULL && NewArgc == 0)
267         usage(1);
268
269     cmnd_status = init_vars(sudo_mode, environ);
270
271 #ifdef HAVE_LDAP
272     validated = sudo_ldap_check(pwflag);
273
274     /* Skip reading /etc/sudoers if LDAP told us to */
275     if (!def_ignore_local_sudoers) {
276         int v;
277
278         check_sudoers();        /* check mode/owner on _PATH_SUDOERS */
279
280         /* Local sudoers file overrides LDAP if we have a match. */
281         v = sudoers_lookup(pwflag);
282         if (validated == VALIDATE_ERROR || ISSET(v, VALIDATE_OK))
283             validated = v;
284     }
285 #else
286     check_sudoers();    /* check mode/owner on _PATH_SUDOERS */
287
288     /* Validate the user but don't search for pseudo-commands. */
289     validated = sudoers_lookup(pwflag);
290 #endif
291     if (safe_cmnd == NULL)
292         safe_cmnd = estrdup(user_cmnd);
293
294     /*
295      * Look up the timestamp dir owner if one is specified.
296      */
297     if (def_timestampowner) {
298         struct passwd *pw;
299
300         if (*def_timestampowner == '#')
301             pw = getpwuid(atoi(def_timestampowner + 1));
302         else
303             pw = getpwnam(def_timestampowner);
304         if (!pw)
305             log_error(0, "timestamp owner (%s): No such user",
306                 def_timestampowner);
307         timestamp_uid = pw->pw_uid;
308     }
309
310     /* This goes after the sudoers parse since we honor sudoers options. */
311     if (sudo_mode == MODE_KILL || sudo_mode == MODE_INVALIDATE) {
312         remove_timestamp((sudo_mode == MODE_KILL));
313         exit(0);
314     }
315
316     if (ISSET(validated, VALIDATE_ERROR))
317         log_error(0, "parse error in %s near line %d", _PATH_SUDOERS,
318             errorlineno);
319
320     /* Is root even allowed to run sudo? */
321     if (user_uid == 0 && !def_root_sudo) {
322         (void) fprintf(stderr,
323             "Sorry, %s has been configured to not allow root to run it.\n",
324             getprogname());
325         exit(1);
326     }
327
328     /* If given the -P option, set the "preserve_groups" flag. */
329     if (ISSET(sudo_mode, MODE_PRESERVE_GROUPS))
330         def_preserve_groups = TRUE;
331
332     /* If no command line args and "set_home" is not set, error out. */
333     if (ISSET(sudo_mode, MODE_IMPLIED_SHELL) && !def_shell_noargs)
334         usage(1);
335
336     /* Bail if a tty is required and we don't have one.  */
337     if (def_requiretty) {
338         if ((fd = open(_PATH_TTY, O_RDWR|O_NOCTTY)) == -1)
339             log_error(NO_MAIL, "sorry, you must have a tty to run sudo");
340         else
341             (void) close(fd);
342     }
343
344     /* User may have overriden environment resetting via the -E flag. */
345     if (ISSET(sudo_mode, MODE_PRESERVE_ENV) && ISSET(validated, FLAG_SETENV))
346         def_env_reset = FALSE;
347
348     /* Build a new environment that avoids any nasty bits. */
349     environ = rebuild_env(environ, sudo_mode, ISSET(validated, FLAG_NOEXEC));
350
351     /* Fill in passwd struct based on user we are authenticating as.  */
352     auth_pw = get_authpw();
353
354     /* Require a password if sudoers says so.  */
355     if (!ISSET(validated, FLAG_NOPASS))
356         check_user(validated);
357
358     /* If run as root with SUDO_USER set, set sudo_user.pw to that user. */
359     if (user_uid == 0 && prev_user != NULL && strcmp(prev_user, "root") != 0) {
360             struct passwd *pw;
361
362             if ((pw = sudo_getpwnam(prev_user)) != NULL) {
363                     efree(sudo_user.pw);
364                     sudo_user.pw = pw;
365             }
366     }
367
368     if (ISSET(validated, VALIDATE_OK)) {
369         /* Finally tell the user if the command did not exist. */
370         if (cmnd_status == NOT_FOUND_DOT) {
371             warnx("ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run.", user_cmnd, user_cmnd, user_cmnd);
372             exit(1);
373         } else if (cmnd_status == NOT_FOUND) {
374             warnx("%s: command not found", user_cmnd);
375             exit(1);
376         }
377
378         /* If user specified env vars make sure sudoers allows it. */
379         if (ISSET(sudo_mode, MODE_RUN) && !ISSET(validated, FLAG_SETENV)) {
380             if (ISSET(sudo_mode, MODE_PRESERVE_ENV))
381                 log_error(NO_MAIL,
382                     "sorry, you are not allowed to preserve the environment");
383             else
384                 validate_env_vars(sudo_user.env_vars);
385         }
386
387         log_auth(validated, 1);
388         if (sudo_mode == MODE_VALIDATE)
389             exit(0);
390         else if (sudo_mode == MODE_LIST) {
391             list_matches();
392 #ifdef HAVE_LDAP
393             sudo_ldap_list_matches();
394 #endif
395             exit(0);
396         }
397
398         /* Override user's umask if configured to do so. */
399         if (def_umask != 0777)
400             (void) umask(def_umask);
401
402         /* Restore coredumpsize resource limit. */
403 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
404         (void) setrlimit(RLIMIT_CORE, &corelimit);
405 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
406
407         /* Become specified user or root if executing a command. */
408         if (ISSET(sudo_mode, MODE_RUN))
409             set_perms(PERM_FULL_RUNAS);
410
411         /* Close the password and group files */
412         endpwent();
413         endgrent();
414
415         if (ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
416             char *p;
417
418             /* Convert /bin/sh -> -sh so shell knows it is a login shell */
419             if ((p = strrchr(NewArgv[0], '/')) == NULL)
420                 p = NewArgv[0];
421             *p = '-';
422             NewArgv[0] = p;
423
424             /* Change to target user's homedir. */
425             if (chdir(runas_pw->pw_dir) == -1)
426                 warn("unable to change directory to %s", runas_pw->pw_dir);
427         }
428
429         if (ISSET(sudo_mode, MODE_EDIT))
430             exit(sudo_edit(NewArgc, NewArgv, envp));
431
432         /* Insert user-specified environment variables. */
433         environ = insert_env_vars(environ, sudo_user.env_vars);
434
435         /* Restore signal handlers before we exec. */
436         (void) sigaction(SIGINT, &saved_sa_int, NULL);
437         (void) sigaction(SIGQUIT, &saved_sa_quit, NULL);
438         (void) sigaction(SIGTSTP, &saved_sa_tstp, NULL);
439
440 #ifndef PROFILING
441         if (ISSET(sudo_mode, MODE_BACKGROUND) && fork() > 0)
442             exit(0);
443         else {
444 #ifdef HAVE_SELINUX
445             if (is_selinux_enabled() > 0 && user_role != NULL)
446                 selinux_exec(user_role, user_type, NewArgv, environ,
447                     ISSET(sudo_mode, MODE_LOGIN_SHELL));
448 #endif
449             execve(safe_cmnd, NewArgv, environ);
450         }
451 #else
452         exit(0);
453 #endif /* PROFILING */
454         /*
455          * If we got here then the exec() failed...
456          */
457         if (errno == ENOEXEC) {
458             NewArgv--;                  /* at least one extra slot... */
459             NewArgv[0] = "sh";
460             NewArgv[1] = safe_cmnd;
461             execve(_PATH_BSHELL, NewArgv, environ);
462         }
463         warn("unable to execute %s", safe_cmnd);
464         exit(127);
465     } else if (ISSET(validated, FLAG_NO_USER) || (validated & FLAG_NO_HOST)) {
466         log_auth(validated, 1);
467         exit(1);
468     } else if (ISSET(validated, VALIDATE_NOT_OK)) {
469         if (def_path_info) {
470             /*
471              * We'd like to not leak path info at all here, but that can
472              * *really* confuse the users.  To really close the leak we'd
473              * have to say "not allowed to run foo" even when the problem
474              * is just "no foo in path" since the user can trivially set
475              * their path to just contain a single dir.
476              */
477             log_auth(validated,
478                 !(cmnd_status == NOT_FOUND_DOT || cmnd_status == NOT_FOUND));
479             if (cmnd_status == NOT_FOUND)
480                 warnx("%s: command not found", user_cmnd);
481             else if (cmnd_status == NOT_FOUND_DOT)
482                 warnx("ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run.", user_cmnd, user_cmnd, user_cmnd);
483         } else {
484             /* Just tell the user they are not allowed to run foo. */
485             log_auth(validated, 1);
486         }
487         exit(1);
488     } else {
489         /* should never get here */
490         log_auth(validated, 1);
491         exit(1);
492     }
493     exit(0);    /* not reached */
494 }
495
496 /*
497  * Initialize timezone, set umask, fill in ``sudo_user'' struct and
498  * load the ``interfaces'' array.
499  */
500 static int
501 init_vars(sudo_mode, envp)
502     int sudo_mode;
503     char **envp;
504 {
505     char *p, **ep, thost[MAXHOSTNAMELEN];
506     int nohostname, rval;
507
508     /* Sanity check command from user. */
509     if (user_cmnd == NULL && strlen(NewArgv[0]) >= PATH_MAX)
510         errx(1, "%s: File name too long", NewArgv[0]);
511
512 #ifdef HAVE_TZSET
513     (void) tzset();             /* set the timezone if applicable */
514 #endif /* HAVE_TZSET */
515
516     /* Default value for cmnd and cwd, overridden later. */
517     if (user_cmnd == NULL)
518         user_cmnd = NewArgv[0];
519     (void) strlcpy(user_cwd, "unknown", sizeof(user_cwd));
520
521     /*
522      * We avoid gethostbyname() if possible since we don't want
523      * sudo to block if DNS or NIS is hosed.
524      * "host" is the (possibly fully-qualified) hostname and
525      * "shost" is the unqualified form of the hostname.
526      */
527     sudo_user.host_fqdn_queried = FALSE;
528     nohostname = gethostname(thost, sizeof(thost));
529     if (nohostname)
530         user_host = user_shost = "localhost";
531     else {
532         user_host = estrdup(thost);
533         if (def_fqdn) {
534             /* Defer call to set_fqdn() until log_error() is safe. */
535             user_shost = user_host;
536         } else {
537             user_shost = user_host;
538         }
539     }
540
541     if ((p = ttyname(STDIN_FILENO)) || (p = ttyname(STDOUT_FILENO))) {
542         user_tty = user_ttypath = estrdup(p);
543         if (strncmp(user_tty, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
544             user_tty += sizeof(_PATH_DEV) - 1;
545     } else
546         user_tty = "unknown";
547
548     for (ep = envp; *ep; ep++) {
549         switch (**ep) {
550             case 'P':
551                 if (strncmp("PATH=", *ep, 5) == 0)
552                     user_path = *ep + 5;
553                 break;
554             case 'S':
555                 if (strncmp("SHELL=", *ep, 6) == 0)
556                     user_shell = *ep + 6;
557                 else if (!user_prompt && strncmp("SUDO_PROMPT=", *ep, 12) == 0)
558                     user_prompt = *ep + 12;
559                 else if (strncmp("SUDO_USER=", *ep, 10) == 0)
560                     prev_user = *ep + 10;
561                 break;
562
563             }
564     }
565
566     /*
567      * Get a local copy of the user's struct passwd with the shadow password
568      * if necessary.  It is assumed that euid is 0 at this point so we
569      * can read the shadow passwd file if necessary.
570      */
571     if ((sudo_user.pw = sudo_getpwuid(getuid())) == NULL) {
572         /* Need to make a fake struct passwd for logging to work. */
573         struct passwd pw;
574         char pw_name[MAX_UID_T_LEN + 1];
575
576         pw.pw_uid = getuid();
577         (void) snprintf(pw_name, sizeof(pw_name), "%lu",
578             (unsigned long) pw.pw_uid);
579         pw.pw_name = pw_name;
580         sudo_user.pw = &pw;
581
582         /*
583          * If we are in -k/-K mode, just spew to stderr.  It is not unusual for
584          * users to place "sudo -k" in a .logout file which can cause sudo to
585          * be run during reboot after the YP/NIS/NIS+/LDAP/etc daemon has died.
586          */
587         if (sudo_mode & (MODE_INVALIDATE|MODE_KILL))
588             errx(1, "uid %s does not exist in the passwd file!", pw_name);
589         log_error(0, "uid %s does not exist in the passwd file!", pw_name);
590     }
591     if (user_shell == NULL || *user_shell == '\0')
592         user_shell = sudo_user.pw->pw_shell;
593
594     /* It is now safe to use log_error() and set_perms() */
595
596 #ifdef HAVE_GETGROUPS
597     if ((user_ngroups = getgroups(0, NULL)) > 0) {
598         user_groups = emalloc2(user_ngroups, sizeof(GETGROUPS_T));
599         if (getgroups(user_ngroups, user_groups) < 0)
600             log_error(USE_ERRNO|MSG_ONLY, "can't get group vector");
601     } else
602         user_ngroups = 0;
603 #endif
604
605     if (def_fqdn)
606         set_fqdn();                     /* may call log_error() */
607
608     if (nohostname)
609         log_error(USE_ERRNO|MSG_ONLY, "can't get hostname");
610
611     set_runaspw(*user_runas);           /* may call log_error() */
612     if (*user_runas[0] == '#' && runas_pw->pw_name && runas_pw->pw_name[0])
613         *user_runas = estrdup(runas_pw->pw_name);
614
615     /*
616      * Get current working directory.  Try as user, fall back to root.
617      */
618     set_perms(PERM_USER);
619     if (!getcwd(user_cwd, sizeof(user_cwd))) {
620         set_perms(PERM_ROOT);
621         if (!getcwd(user_cwd, sizeof(user_cwd))) {
622             warnx("cannot get working directory");
623             (void) strlcpy(user_cwd, "unknown", sizeof(user_cwd));
624         }
625     } else
626         set_perms(PERM_ROOT);
627
628     /*
629      * If we were given the '-e', '-i' or '-s' options we need to redo
630      * NewArgv and NewArgc.
631      */
632     if ((sudo_mode & (MODE_SHELL | MODE_EDIT))) {
633         char **dst, **src = NewArgv;
634
635         /* Allocate an extra slot for execve() failure (ENOEXEC). */
636         NewArgv = (char **) emalloc2((++NewArgc + 2), sizeof(char *));
637         NewArgv++;
638         if (ISSET(sudo_mode, MODE_EDIT))
639             NewArgv[0] = "sudoedit";
640         else if (ISSET(sudo_mode, MODE_LOGIN_SHELL))
641             NewArgv[0] = runas_pw->pw_shell;
642         else if (user_shell && *user_shell)
643             NewArgv[0] = user_shell;
644         else
645             errx(1, "unable to determine shell");
646
647         /* copy the args from NewArgv */
648         for (dst = NewArgv + 1; (*dst = *src) != NULL; ++src, ++dst)
649             continue;
650     }
651
652     /* Set login class if applicable. */
653     set_loginclass(sudo_user.pw);
654
655     /* Set project if applicable. */
656     set_project(runas_pw);
657
658     /* Resolve the path and return. */
659     rval = FOUND;
660     user_stat = emalloc(sizeof(struct stat));
661     if (sudo_mode & (MODE_RUN | MODE_EDIT)) {
662         if (ISSET(sudo_mode, MODE_RUN)) {
663             /* XXX - default_runas may be modified during parsing of sudoers */
664             set_perms(PERM_RUNAS);
665             rval = find_path(NewArgv[0], &user_cmnd, user_stat, user_path);
666             set_perms(PERM_ROOT);
667             if (rval != FOUND) {
668                 /* Failed as root, try as invoking user. */
669                 set_perms(PERM_USER);
670                 rval = find_path(NewArgv[0], &user_cmnd, user_stat, user_path);
671                 set_perms(PERM_ROOT);
672             }
673         }
674
675         /* set user_args */
676         if (NewArgc > 1) {
677             char *to, **from;
678             size_t size, n;
679
680             /* If we didn't realloc NewArgv it is contiguous so just count. */
681             if (!(sudo_mode & (MODE_SHELL | MODE_EDIT))) {
682                 size = (size_t) (NewArgv[NewArgc-1] - NewArgv[1]) +
683                         strlen(NewArgv[NewArgc-1]) + 1;
684             } else {
685                 for (size = 0, from = NewArgv + 1; *from; from++)
686                     size += strlen(*from) + 1;
687             }
688
689             /* Alloc and build up user_args. */
690             user_args = (char *) emalloc(size);
691             for (to = user_args, from = NewArgv + 1; *from; from++) {
692                 n = strlcpy(to, *from, size - (to - user_args));
693                 if (n >= size - (to - user_args))
694                     errx(1, "internal error, init_vars() overflow");
695                 to += n;
696                 *to++ = ' ';
697             }
698             *--to = '\0';
699         }
700     }
701     if ((user_base = strrchr(user_cmnd, '/')) != NULL)
702         user_base++;
703     else
704         user_base = user_cmnd;
705
706     return(rval);
707 }
708
709 /*
710  * Command line argument parsing, can't use getopt(3).
711  */
712 static int
713 parse_args(argc, argv)
714     int argc;
715     char **argv;
716 {
717     int rval = MODE_RUN;                /* what mode is sudo to be run in? */
718     int excl = 0;                       /* exclusive arg, no others allowed */
719
720     NewArgv = argv + 1;
721     NewArgc = argc - 1;
722
723     /* First, check to see if we were invoked as "sudoedit". */
724     if (strcmp(getprogname(), "sudoedit") == 0) {
725         rval = MODE_EDIT;
726         excl = 'e';
727     } else
728         rval = MODE_RUN;
729
730     while (NewArgc > 0) {
731         if (NewArgv[0][0] == '-') {
732             if (NewArgv[0][1] != '\0' && NewArgv[0][2] != '\0') {
733                 warnx("please use single character options");
734                 usage(1);
735             }
736
737             switch (NewArgv[0][1]) {
738                 case 'p':
739                     /* Must have an associated prompt. */
740                     if (NewArgv[1] == NULL)
741                         usage(1);
742
743                     user_prompt = NewArgv[1];
744                     def_passprompt_override = TRUE;
745
746                     NewArgc--;
747                     NewArgv++;
748                     break;
749                 case 'u':
750                     /* Must have an associated runas user. */
751                     if (NewArgv[1] == NULL)
752                         usage(1);
753
754                     user_runas = &NewArgv[1];
755
756                     NewArgc--;
757                     NewArgv++;
758                     break;
759 #ifdef HAVE_BSD_AUTH_H
760                 case 'a':
761                     /* Must have an associated authentication style. */
762                     if (NewArgv[1] == NULL)
763                         usage(1);
764
765                     login_style = NewArgv[1];
766
767                     NewArgc--;
768                     NewArgv++;
769                     break;
770 #endif
771 #ifdef HAVE_LOGIN_CAP_H
772                 case 'c':
773                     /* Must have an associated login class. */
774                     if (NewArgv[1] == NULL)
775                         usage(1);
776
777                     login_class = NewArgv[1];
778                     def_use_loginclass = TRUE;
779
780                     NewArgc--;
781                     NewArgv++;
782                     break;
783 #endif
784                 case 'b':
785                     SET(rval, MODE_BACKGROUND);
786                     break;
787                 case 'e':
788                     rval = MODE_EDIT;
789                     if (excl && excl != 'e')
790                         usage_excl(1);
791                     excl = 'e';
792                     break;
793                 case 'v':
794                     rval = MODE_VALIDATE;
795                     if (excl && excl != 'v')
796                         usage_excl(1);
797                     excl = 'v';
798                     break;
799                 case 'i':
800                     SET(rval, (MODE_LOGIN_SHELL | MODE_SHELL));
801                     def_env_reset = TRUE;
802                     if (excl && excl != 'i')
803                         usage_excl(1);
804                     excl = 'i';
805                     break;
806                 case 'k':
807                     rval = MODE_INVALIDATE;
808                     if (excl && excl != 'k')
809                         usage_excl(1);
810                     excl = 'k';
811                     break;
812                 case 'K':
813                     rval = MODE_KILL;
814                     if (excl && excl != 'K')
815                         usage_excl(1);
816                     excl = 'K';
817                     break;
818                 case 'L':
819                     rval = MODE_LISTDEFS;
820                     if (excl && excl != 'L')
821                         usage_excl(1);
822                     excl = 'L';
823                     break;
824                 case 'l':
825                     rval = MODE_LIST;
826                     if (excl && excl != 'l')
827                         usage_excl(1);
828                     excl = 'l';
829                     break;
830                 case 'V':
831                     rval = MODE_VERSION;
832                     if (excl && excl != 'V')
833                         usage_excl(1);
834                     excl = 'V';
835                     break;
836                 case 'h':
837                     rval = MODE_HELP;
838                     if (excl && excl != 'h')
839                         usage_excl(1);
840                     excl = 'h';
841                     break;
842                 case 's':
843                     SET(rval, MODE_SHELL);
844                     if (excl && excl != 's')
845                         usage_excl(1);
846                     excl = 's';
847                     break;
848                 case 'H':
849                     SET(rval, MODE_RESET_HOME);
850                     break;
851                 case 'P':
852                     SET(rval, MODE_PRESERVE_GROUPS);
853                     break;
854                 case 'S':
855                     SET(tgetpass_flags, TGP_STDIN);
856                     break;
857                 case 'E':
858                     SET(rval, MODE_PRESERVE_ENV);
859                     break;
860 #ifdef HAVE_SELINUX
861                 case 'r':
862                     /* Must have an associated SELinux role. */
863                     if (NewArgv[1] == NULL)
864                         usage(1);
865
866                     user_role = NewArgv[1];
867
868                     NewArgc--;
869                     NewArgv++;
870                     break;
871                 case 't':
872                     /* Must have an associated SELinux type. */
873                     if (NewArgv[1] == NULL)
874                         usage(1);
875
876                     user_type = NewArgv[1];
877
878                     NewArgc--;
879                     NewArgv++;
880                     break;
881 #endif
882                 case '-':
883                     NewArgc--;
884                     NewArgv++;
885                     goto args_done;
886                 case '\0':
887                     warnx("'-' requires an argument");
888                     usage(1);
889                 default:
890                     warnx("illegal option `%s'", NewArgv[0]);
891                     usage(1);
892             }
893         } else if (NewArgv[0][0] != '/' && strchr(NewArgv[0], '=') != NULL) {
894             /* Could be an environment variable. */
895             struct list_member *ev;
896             ev = emalloc(sizeof(*ev));
897             ev->value = NewArgv[0];
898             ev->next = sudo_user.env_vars;
899             sudo_user.env_vars = ev;
900         } else {
901             /* Not an arg */
902             break;
903         }
904         NewArgc--;
905         NewArgv++;
906     }
907 args_done:
908
909     if (ISSET(rval, MODE_EDIT) &&
910         (ISSET(rval, MODE_PRESERVE_ENV) || sudo_user.env_vars != NULL)) {
911         if (ISSET(rval, MODE_PRESERVE_ENV))
912             warnx("the `-E' option is not valid in edit mode");
913         if (sudo_user.env_vars != NULL)
914             warnx("you may not specify environment variables in edit mode");
915         usage(1);
916     }
917     if (ISSET(rval, MODE_PRESERVE_ENV) && ISSET(rval, MODE_LOGIN_SHELL)) {
918         warnx("you may not specify both the `-i' and `-E' options");
919         usage(1);
920     }
921     if (user_runas != NULL && !ISSET(rval, (MODE_EDIT|MODE_RUN))) {
922         if (excl != '\0')
923             warnx("the `-u' and '-%c' options may not be used together", excl);
924         usage(1);
925     }
926     if ((NewArgc == 0 && (rval & MODE_EDIT)) ||
927         (NewArgc > 0 && !(rval & (MODE_RUN | MODE_EDIT))))
928         usage(1);
929     if (NewArgc == 0 && rval == MODE_RUN)
930         SET(rval, (MODE_IMPLIED_SHELL | MODE_SHELL));
931
932     return(rval);
933 }
934
935 /*
936  * Sanity check sudoers mode/owner/type.
937  * Leaves a file pointer to the sudoers file open in ``fp''.
938  */
939 static void
940 check_sudoers()
941 {
942     struct stat statbuf;
943     int rootstat, i;
944
945     /*
946      * Fix the mode and group on sudoers file from old default.
947      * Only works if file system is readable/writable by root.
948      */
949     if ((rootstat = stat_sudoers(_PATH_SUDOERS, &statbuf)) == 0 &&
950         SUDOERS_UID == statbuf.st_uid && SUDOERS_MODE != 0400 &&
951         (statbuf.st_mode & 0007777) == 0400) {
952
953         if (chmod(_PATH_SUDOERS, SUDOERS_MODE) == 0) {
954             warnx("fixed mode on %s", _PATH_SUDOERS);
955             SET(statbuf.st_mode, SUDOERS_MODE);
956             if (statbuf.st_gid != SUDOERS_GID) {
957                 if (!chown(_PATH_SUDOERS,(uid_t) -1,SUDOERS_GID)) {
958                     warnx("set group on %s", _PATH_SUDOERS);
959                     statbuf.st_gid = SUDOERS_GID;
960                 } else
961                     warn("unable to set group on %s", _PATH_SUDOERS);
962             }
963         } else
964             warn("unable to fix mode on %s", _PATH_SUDOERS);
965     }
966
967     /*
968      * Sanity checks on sudoers file.  Must be done as sudoers
969      * file owner.  We already did a stat as root, so use that
970      * data if we can't stat as sudoers file owner.
971      */
972     set_perms(PERM_SUDOERS);
973
974     if (rootstat != 0 && stat_sudoers(_PATH_SUDOERS, &statbuf) != 0)
975         log_error(USE_ERRNO, "can't stat %s", _PATH_SUDOERS);
976     else if (!S_ISREG(statbuf.st_mode))
977         log_error(0, "%s is not a regular file", _PATH_SUDOERS);
978     else if (statbuf.st_size == 0)
979         log_error(0, "%s is zero length", _PATH_SUDOERS);
980     else if ((statbuf.st_mode & 07777) != SUDOERS_MODE)
981         log_error(0, "%s is mode 0%o, should be 0%o", _PATH_SUDOERS,
982             (unsigned int) (statbuf.st_mode & 07777),
983             (unsigned int) SUDOERS_MODE);
984     else if (statbuf.st_uid != SUDOERS_UID)
985         log_error(0, "%s is owned by uid %lu, should be %lu", _PATH_SUDOERS,
986             (unsigned long) statbuf.st_uid, (unsigned long) SUDOERS_UID);
987     else if (statbuf.st_gid != SUDOERS_GID)
988         log_error(0, "%s is owned by gid %lu, should be %lu", _PATH_SUDOERS,
989             (unsigned long) statbuf.st_gid, (unsigned long) SUDOERS_GID);
990     else {
991         /* Solaris sometimes returns EAGAIN so try 10 times */
992         for (i = 0; i < 10 ; i++) {
993             errno = 0;
994             if ((sudoers_fp = fopen(_PATH_SUDOERS, "r")) == NULL ||
995                 fgetc(sudoers_fp) == EOF) {
996                 if (sudoers_fp != NULL)
997                     fclose(sudoers_fp);
998                 sudoers_fp = NULL;
999                 if (errno != EAGAIN && errno != EWOULDBLOCK)
1000                     break;
1001             } else
1002                 break;
1003             sleep(1);
1004         }
1005         if (sudoers_fp == NULL)
1006             log_error(USE_ERRNO, "can't open %s", _PATH_SUDOERS);
1007     }
1008
1009     set_perms(PERM_ROOT);               /* change back to root */
1010 }
1011
1012 /*
1013  * Close all open files (except std*) and turn off core dumps.
1014  */
1015 static void
1016 initial_setup()
1017 {
1018     int miss[3], devnull = -1;
1019 #if defined(__linux__) || (defined(RLIMIT_CORE) && !defined(SUDO_DEVEL))
1020     struct rlimit rl;
1021 #endif
1022
1023 #if defined(__linux__)
1024     /*
1025      * Unlimit the number of processes since Linux's setuid() will
1026      * apply resource limits when changing uid and return EAGAIN if
1027      * nproc would be violated by the uid switch.
1028      */
1029     rl.rlim_cur = rl.rlim_max = RLIM_INFINITY;
1030     if (setrlimit(RLIMIT_NPROC, &rl)) {
1031         if (getrlimit(RLIMIT_NPROC, &rl) == 0) {
1032             rl.rlim_cur = rl.rlim_max;
1033             (void)setrlimit(RLIMIT_NPROC, &rl);
1034         }
1035     }
1036 #endif /* __linux__ */
1037 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
1038     /*
1039      * Turn off core dumps.
1040      */
1041     (void) getrlimit(RLIMIT_CORE, &corelimit);
1042     memcpy(&rl, &corelimit, sizeof(struct rlimit));
1043     rl.rlim_cur = 0;
1044     (void) setrlimit(RLIMIT_CORE, &rl);
1045 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
1046
1047     /*
1048      * stdin, stdout and stderr must be open; set them to /dev/null
1049      * if they are closed and close all other fds.
1050      */
1051     miss[STDIN_FILENO] = fcntl(STDIN_FILENO, F_GETFL, 0) == -1;
1052     miss[STDOUT_FILENO] = fcntl(STDOUT_FILENO, F_GETFL, 0) == -1;
1053     miss[STDERR_FILENO] = fcntl(STDERR_FILENO, F_GETFL, 0) == -1;
1054     if (miss[STDIN_FILENO] || miss[STDOUT_FILENO] || miss[STDERR_FILENO]) {
1055         if ((devnull = open(_PATH_DEVNULL, O_RDWR, 0644)) != -1) {
1056             if (miss[STDIN_FILENO])
1057                 (void) dup2(devnull, STDIN_FILENO);
1058             if (miss[STDOUT_FILENO])
1059                 (void) dup2(devnull, STDOUT_FILENO);
1060             if (miss[STDERR_FILENO])
1061                 (void) dup2(devnull, STDERR_FILENO);
1062         }
1063     }
1064     closefrom(STDERR_FILENO + 1);
1065 }
1066
1067 #ifdef HAVE_LOGIN_CAP_H
1068 static void
1069 set_loginclass(pw)
1070     struct passwd *pw;
1071 {
1072     int errflags;
1073
1074     /*
1075      * Don't make it a fatal error if the user didn't specify the login
1076      * class themselves.  We do this because if login.conf gets
1077      * corrupted we want the admin to be able to use sudo to fix it.
1078      */
1079     if (login_class)
1080         errflags = NO_MAIL|MSG_ONLY;
1081     else
1082         errflags = NO_MAIL|MSG_ONLY|NO_EXIT;
1083
1084     if (login_class && strcmp(login_class, "-") != 0) {
1085         if (strcmp(*user_runas, "root") != 0 && user_uid != 0)
1086             errx(1, "only root can use -c %s", login_class);
1087     } else {
1088         login_class = pw->pw_class;
1089         if (!login_class || !*login_class)
1090             login_class =
1091                 (pw->pw_uid == 0) ? LOGIN_DEFROOTCLASS : LOGIN_DEFCLASS;
1092     }
1093
1094     lc = login_getclass(login_class);
1095     if (!lc || !lc->lc_class || strcmp(lc->lc_class, login_class) != 0) {
1096         log_error(errflags, "unknown login class: %s", login_class);
1097         if (!lc)
1098             lc = login_getclass(NULL);  /* needed for login_getstyle() later */
1099     }
1100 }
1101 #else
1102 static void
1103 set_loginclass(pw)
1104     struct passwd *pw;
1105 {
1106 }
1107 #endif /* HAVE_LOGIN_CAP_H */
1108
1109 #ifdef HAVE_PROJECT_H
1110 static void
1111 set_project(pw)
1112     struct passwd *pw;
1113 {
1114     int errflags = NO_MAIL|MSG_ONLY|NO_EXIT;
1115     int errval;
1116     struct project proj;
1117     struct project *resultp = '\0';
1118     char buf[1024];
1119
1120     /*
1121      * Collect the default project for the user and settaskid
1122      */
1123     setprojent();
1124     if (resultp = getdefaultproj(pw->pw_name, &proj, buf, sizeof(buf))) {
1125         errval = setproject(resultp->pj_name, pw->pw_name, TASK_NORMAL);
1126         if (errval != 0) {
1127             switch(errval) {
1128             case SETPROJ_ERR_TASK:
1129                 if (errno == EAGAIN)
1130                     log_error(errflags, "resource control limit has been reached");
1131                 else if (errno == ESRCH)
1132                     log_error(errflags, "user \"%s\" is not a member of "
1133                         "project \"%s\"", pw->pw_name, resultp->pj_name);
1134                 else if (errno == EACCES)
1135                     log_error(errflags, "the invoking task is final");
1136                 else
1137                     log_error(errflags, "could not join project \"%s\"",
1138                         resultp->pj_name);
1139                 break;
1140             case SETPROJ_ERR_POOL:
1141                 if (errno == EACCES)
1142                     log_error(errflags, "no resource pool accepting "
1143                             "default bindings exists for project \"%s\"",
1144                             resultp->pj_name);
1145                 else if (errno == ESRCH)
1146                     log_error(errflags, "specified resource pool does "
1147                             "not exist for project \"%s\"", resultp->pj_name);
1148                 else
1149                     log_error(errflags, "could not bind to default "
1150                             "resource pool for project \"%s\"", resultp->pj_name);
1151                 break;
1152             default:
1153                 if (errval <= 0) {
1154                     log_error(errflags, "setproject failed for project \"%s\"",
1155                         resultp->pj_name);
1156                 } else {
1157                     log_error(errflags, "warning, resource control assignment "
1158                         "failed for project \"%s\"", resultp->pj_name);
1159                 }
1160             }
1161         }
1162     } else {
1163         log_error(errflags, "getdefaultproj() error: %s", strerror(errno));
1164     }
1165     endprojent();
1166 }
1167 #else
1168 static void
1169 set_project(pw)
1170     struct passwd *pw;
1171 {
1172 }
1173 #endif /* HAVE_PROJECT_H */
1174
1175 /*
1176  * Look up the fully qualified domain name and set user_host and user_shost.
1177  */
1178 void
1179 set_fqdn()
1180 {
1181 #ifdef HAVE_GETADDRINFO
1182     struct addrinfo *res0, hint;
1183 #else
1184     struct hostent *hp;
1185 #endif
1186     char *p;
1187
1188 #ifdef HAVE_GETADDRINFO
1189     memset(&hint, 0, sizeof(hint));
1190     hint.ai_family = PF_UNSPEC;
1191     hint.ai_flags = AI_CANONNAME;
1192     if (getaddrinfo(user_host, NULL, &hint, &res0) != 0) {
1193 #else
1194     if (!(hp = gethostbyname(user_host))) {
1195 #endif
1196         log_error(MSG_ONLY|NO_EXIT,
1197             "unable to resolve host %s", user_host);
1198     } else {
1199         if (user_shost != user_host)
1200             efree(user_shost);
1201         efree(user_host);
1202 #ifdef HAVE_GETADDRINFO
1203         user_host = estrdup(res0->ai_canonname);
1204         freeaddrinfo(res0);
1205 #else
1206         user_host = estrdup(hp->h_name);
1207 #endif
1208     }
1209     if ((p = strchr(user_host, '.'))) {
1210         *p = '\0';
1211         user_shost = estrdup(user_host);
1212         *p = '.';
1213     } else {
1214         user_shost = user_host;
1215     }
1216     sudo_user.host_fqdn_queried = TRUE;
1217 }
1218
1219 /*
1220  * Get passwd entry for the user we are going to run commands as.
1221  * By default, this is "root".  Updates runas_pw as a side effect.
1222  */
1223 int
1224 set_runaspw(user)
1225     char *user;
1226 {
1227     if (runas_pw != NULL) {
1228         if (user_runas != &def_runas_default)
1229             return(TRUE);               /* don't override -u option */
1230         efree(runas_pw);
1231     }
1232     if (*user == '#') {
1233         runas_pw = sudo_getpwuid(atoi(user + 1));
1234         if (runas_pw == NULL) {
1235             runas_pw = emalloc(sizeof(struct passwd));
1236             (void) memset((VOID *)runas_pw, 0, sizeof(struct passwd));
1237             runas_pw->pw_uid = atoi(user + 1);
1238         }
1239     } else {
1240         runas_pw = sudo_getpwnam(user);
1241         if (runas_pw == NULL)
1242             log_error(NO_MAIL|MSG_ONLY, "no passwd entry for %s!", user);
1243     }
1244     runas_resetgroups();
1245     return(TRUE);
1246 }
1247
1248 /*
1249  * Get passwd entry for the user we are going to authenticate as.
1250  * By default, this is the user invoking sudo.  In the most common
1251  * case, this matches sudo_user.pw or runas_pw.
1252  */
1253 static struct passwd *
1254 get_authpw()
1255 {
1256     struct passwd *pw;
1257
1258     if (def_rootpw) {
1259         if (runas_pw->pw_uid == 0)
1260             pw = runas_pw;
1261         else if ((pw = sudo_getpwuid(0)) == NULL)
1262             log_error(0, "uid 0 does not exist in the passwd file!");
1263     } else if (def_runaspw) {
1264         if (strcmp(def_runas_default, *user_runas) == 0)
1265             pw = runas_pw;
1266         else if ((pw = sudo_getpwnam(def_runas_default)) == NULL)
1267             log_error(0, "user %s does not exist in the passwd file!",
1268                 def_runas_default);
1269     } else if (def_targetpw) {
1270         if (runas_pw->pw_name == NULL)
1271             log_error(NO_MAIL|MSG_ONLY, "no passwd entry for %lu!",
1272                 (unsigned long) runas_pw->pw_uid);
1273         pw = runas_pw;
1274     } else
1275         pw = sudo_user.pw;
1276
1277     return(pw);
1278 }
1279
1280 /*
1281  * Tell which options are mutually exclusive and exit.
1282  */
1283 static void
1284 usage_excl(exit_val)
1285     int exit_val;
1286 {
1287     warnx("Only one of the -e, -h, i, -k, -K, -l, -s, -v or -V options may be used");
1288     usage(exit_val);
1289 }
1290
1291 /*
1292  * Give usage message and exit.
1293  */
1294 static void
1295 usage(exit_val)
1296     int exit_val;
1297 {
1298     char **p, **uvec[4];
1299     int i, linelen, linemax, ulen, plen;
1300     static char *uvec1[] = {
1301         " -h |",
1302         " -K |",
1303         " -k |",
1304         " -L |",
1305         " -l |",
1306         " -V |",
1307         " -v",
1308         NULL
1309     };
1310     static char *uvec2[] = {
1311         " [-bEHPS]",
1312 #ifdef HAVE_BSD_AUTH_H
1313         " [-a auth_type]",
1314 #endif
1315 #ifdef HAVE_LOGIN_CAP_H
1316         " [-c class|-]",
1317 #endif
1318 #ifdef HAVE_SELINUX
1319         " [-r role]",
1320 #endif
1321         " [-p prompt]",
1322 #ifdef HAVE_SELINUX
1323         " [-t type]",
1324 #endif
1325         " [-u username|#uid]",
1326         " [VAR=value]",
1327         " {-i | -s | <command>}",
1328         NULL
1329     };
1330     static char *uvec3[] = {
1331         " -e",
1332         " [-S]",
1333 #ifdef HAVE_BSD_AUTH_H
1334         " [-a auth_type]",
1335 #endif
1336 #ifdef HAVE_LOGIN_CAP_H
1337         " [-c class|-]",
1338 #endif
1339         " [-p prompt]",
1340         " [-u username|#uid]",
1341         " file ...",
1342         NULL
1343     };
1344
1345     /*
1346      * Use usage vectors appropriate to the progname.
1347      */
1348     if (strcmp(getprogname(), "sudoedit") == 0) {
1349         uvec[0] = uvec3 + 1;
1350         uvec[1] = NULL;
1351     } else {
1352         uvec[0] = uvec1;
1353         uvec[1] = uvec2;
1354         uvec[2] = uvec3;
1355         uvec[3] = NULL;
1356     }
1357
1358     /*
1359      * Print usage and wrap lines as needed.
1360      * Assumes an 80-character wide terminal, which is kind of bogus...
1361      */
1362     ulen = (int)strlen(getprogname()) + 7;
1363     linemax = 80;
1364     for (i = 0; uvec[i] != NULL; i++) {
1365         printf("usage: %s", getprogname());
1366         linelen = linemax - ulen;
1367         for (p = uvec[i]; *p != NULL; p++) {
1368             plen = (int)strlen(*p);
1369             if (linelen >= plen || linelen == linemax - ulen) {
1370                 fputs(*p, stdout);
1371                 linelen -= plen;
1372             } else {
1373                 p--;
1374                 linelen = linemax - ulen;
1375                 printf("\n%*s", ulen, "");
1376             }
1377         }
1378         putchar('\n');
1379     }
1380     exit(exit_val);
1381 }