Imported Debian patch 1.6.9p10-1
[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
100 #include "sudo.h"
101 #include "interfaces.h"
102 #include "version.h"
103
104 #ifndef lint
105 __unused __unused static const char rcsid[] = "$Sudo: sudo.c,v 1.369.2.34 2007/12/13 14:12:49 millert Exp $";
106 #endif /* lint */
107
108 /*
109  * Prototypes
110  */
111 static int init_vars                    __P((int, char **));
112 static int parse_args                   __P((int, char **));
113 static void check_sudoers               __P((void));
114 static void initial_setup               __P((void));
115 static void set_loginclass              __P((struct passwd *));
116 static void set_project                 __P((struct passwd *));
117 static void usage                       __P((int))
118                                             __attribute__((__noreturn__));
119 static void usage_excl                  __P((int))
120                                             __attribute__((__noreturn__));
121 static void usage_excl                  __P((int));
122 static struct passwd *get_authpw        __P((void));
123 extern int sudo_edit                    __P((int, char **, char **));
124 extern void list_matches                __P((void));
125 extern char **rebuild_env               __P((char **, int, int));
126 extern void validate_env_vars           __P((struct list_member *));
127 extern char **insert_env_vars           __P((char **, struct list_member *));
128 extern struct passwd *sudo_getpwnam     __P((const char *));
129 extern struct passwd *sudo_getpwuid     __P((uid_t));
130 extern struct passwd *sudo_pwdup        __P((const struct passwd *));
131
132 /*
133  * Globals
134  */
135 int Argc, NewArgc;
136 char **Argv, **NewArgv;
137 char *prev_user;
138 struct sudo_user sudo_user;
139 struct passwd *auth_pw;
140 FILE *sudoers_fp;
141 struct interface *interfaces;
142 int num_interfaces;
143 int tgetpass_flags;
144 uid_t timestamp_uid;
145 extern int errorlineno;
146 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
147 static struct rlimit corelimit;
148 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
149 #ifdef HAVE_LOGIN_CAP_H
150 login_cap_t *lc;
151 #endif /* HAVE_LOGIN_CAP_H */
152 #ifdef HAVE_BSD_AUTH_H
153 char *login_style;
154 #endif /* HAVE_BSD_AUTH_H */
155 sigaction_t saved_sa_int, saved_sa_quit, saved_sa_tstp, saved_sa_chld;
156
157
158 int
159 main(argc, argv, envp)
160     int argc;
161     char **argv;
162     char **envp;
163 {
164     int validated;
165     int fd;
166     int cmnd_status;
167     int sudo_mode;
168     int pwflag;
169     sigaction_t sa;
170     extern int printmatches;
171     extern char **environ;
172
173 #ifdef HAVE_SETLOCALE
174     setlocale(LC_ALL, "");
175 #endif
176
177     Argv = argv;
178     if ((Argc = argc) < 1)
179         usage(1);
180
181     /* Must be done as the first thing... */
182 #if defined(HAVE_GETPRPWNAM) && defined(HAVE_SET_AUTH_PARAMETERS)
183     (void) set_auth_parameters(Argc, Argv);
184 # ifdef HAVE_INITPRIVS
185     initprivs();
186 # endif
187 #endif /* HAVE_GETPRPWNAM && HAVE_SET_AUTH_PARAMETERS */
188
189     if (geteuid() != 0)
190         errx(1, "must be setuid root");
191
192     /*
193      * Signal setup:
194      *  Ignore keyboard-generated signals so the user cannot interrupt
195      *  us at some point and avoid the logging.
196      *  Install handler to wait for children when they exit.
197      */
198     sigemptyset(&sa.sa_mask);
199     sa.sa_flags = SA_RESTART;
200     sa.sa_handler = SIG_IGN;
201     (void) sigaction(SIGINT, &sa, &saved_sa_int);
202     (void) sigaction(SIGQUIT, &sa, &saved_sa_quit);
203     (void) sigaction(SIGTSTP, &sa, &saved_sa_tstp);
204     sa.sa_handler = reapchild;
205     (void) sigaction(SIGCHLD, &sa, &saved_sa_chld);
206
207     /*
208      * Turn off core dumps and close open files.
209      */
210     initial_setup();
211     setpwent();
212
213     /* Parse our arguments. */
214     sudo_mode = parse_args(Argc, Argv);
215
216     /* Setup defaults data structures. */
217     init_defaults();
218
219     /* Load the list of local ip addresses and netmasks.  */
220     load_interfaces();
221
222     pwflag = 0;
223     if (ISSET(sudo_mode, MODE_SHELL))
224         user_cmnd = "shell";
225     else if (ISSET(sudo_mode, MODE_EDIT))
226         user_cmnd = "sudoedit";
227     else
228         switch (sudo_mode) {
229             case MODE_VERSION:
230                 (void) printf("Sudo version %s\n", version);
231                 if (getuid() == 0) {
232                     putchar('\n');
233                     (void) printf("Sudoers path: %s\n", _PATH_SUDOERS);
234                     dump_auth_methods();
235                     dump_defaults();
236                     dump_interfaces();
237                 }
238                 exit(0);
239                 break;
240             case MODE_HELP:
241                 usage(0);
242                 break;
243             case MODE_VALIDATE:
244                 user_cmnd = "validate";
245                 pwflag = I_VERIFYPW;
246                 break;
247             case MODE_KILL:
248             case MODE_INVALIDATE:
249                 user_cmnd = "kill";
250                 pwflag = -1;
251                 break;
252             case MODE_LISTDEFS:
253                 list_options();
254                 exit(0);
255                 break;
256             case MODE_LIST:
257                 user_cmnd = "list";
258                 pwflag = I_LISTPW;
259                 printmatches = 1;
260                 break;
261         }
262
263     /* Must have a command to run... */
264     if (user_cmnd == NULL && NewArgc == 0)
265         usage(1);
266
267     cmnd_status = init_vars(sudo_mode, environ);
268
269 #ifdef HAVE_LDAP
270     validated = sudo_ldap_check(pwflag);
271
272     /* Skip reading /etc/sudoers if LDAP told us to */
273     if (def_ignore_local_sudoers); /* skips */
274     else if (ISSET(validated, VALIDATE_OK) && !printmatches); /* skips */
275     else if (ISSET(validated, VALIDATE_OK) && printmatches)
276     {
277         check_sudoers();        /* check mode/owner on _PATH_SUDOERS */
278
279         /* User is found in LDAP and we want a list of all sudo commands the
280          * user can do, so consult sudoers but throw away result.
281          */
282         sudoers_lookup(pwflag);
283     }
284     else
285 #endif
286     {
287         check_sudoers();        /* check mode/owner on _PATH_SUDOERS */
288
289         /* Validate the user but don't search for pseudo-commands. */
290         validated = sudoers_lookup(pwflag);
291     }
292     if (safe_cmnd == NULL)
293         safe_cmnd = estrdup(user_cmnd);
294
295     /*
296      * Look up the timestamp dir owner if one is specified.
297      */
298     if (def_timestampowner) {
299         struct passwd *pw;
300
301         if (*def_timestampowner == '#')
302             pw = getpwuid(atoi(def_timestampowner + 1));
303         else
304             pw = getpwnam(def_timestampowner);
305         if (!pw)
306             log_error(0, "timestamp owner (%s): No such user",
307                 def_timestampowner);
308         timestamp_uid = pw->pw_uid;
309     }
310
311     /* This goes after the sudoers parse since we honor sudoers options. */
312     if (sudo_mode == MODE_KILL || sudo_mode == MODE_INVALIDATE) {
313         remove_timestamp((sudo_mode == MODE_KILL));
314         exit(0);
315     }
316
317     if (ISSET(validated, VALIDATE_ERROR))
318         log_error(0, "parse error in %s near line %d", _PATH_SUDOERS,
319             errorlineno);
320
321     /* Is root even allowed to run sudo? */
322     if (user_uid == 0 && !def_root_sudo) {
323         (void) fprintf(stderr,
324             "Sorry, %s has been configured to not allow root to run it.\n",
325             getprogname());
326         exit(1);
327     }
328
329     /* If given the -P option, set the "preserve_groups" flag. */
330     if (ISSET(sudo_mode, MODE_PRESERVE_GROUPS))
331         def_preserve_groups = TRUE;
332
333     /* If no command line args and "set_home" is not set, error out. */
334     if (ISSET(sudo_mode, MODE_IMPLIED_SHELL) && !def_shell_noargs)
335         usage(1);
336
337     /* Bail if a tty is required and we don't have one.  */
338     if (def_requiretty) {
339         if ((fd = open(_PATH_TTY, O_RDWR|O_NOCTTY)) == -1)
340             log_error(NO_MAIL, "sorry, you must have a tty to run sudo");
341         else
342             (void) close(fd);
343     }
344
345     /* User may have overriden environment resetting via the -E flag. */
346     if (ISSET(sudo_mode, MODE_PRESERVE_ENV) && ISSET(validated, FLAG_SETENV))
347         def_env_reset = FALSE;
348
349     /* Build a new environment that avoids any nasty bits. */
350     environ = rebuild_env(environ, sudo_mode, ISSET(validated, FLAG_NOEXEC));
351
352     /* Fill in passwd struct based on user we are authenticating as.  */
353     auth_pw = get_authpw();
354
355     /* Require a password if sudoers says so.  */
356     if (!ISSET(validated, FLAG_NOPASS))
357         check_user(validated);
358
359     /* If run as root with SUDO_USER set, set sudo_user.pw to that user. */
360     if (user_uid == 0 && prev_user != NULL && strcmp(prev_user, "root") != 0) {
361             struct passwd *pw;
362
363             if ((pw = sudo_getpwnam(prev_user)) != NULL) {
364                     efree(sudo_user.pw);
365                     sudo_user.pw = pw;
366             }
367     }
368
369     if (ISSET(validated, VALIDATE_OK)) {
370         /* Finally tell the user if the command did not exist. */
371         if (cmnd_status == NOT_FOUND_DOT) {
372             warnx("ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run.", user_cmnd, user_cmnd, user_cmnd);
373             exit(1);
374         } else if (cmnd_status == NOT_FOUND) {
375             warnx("%s: command not found", user_cmnd);
376             exit(1);
377         }
378
379         /* If user specified env vars make sure sudoers allows it. */
380         if (ISSET(sudo_mode, MODE_RUN) && !ISSET(validated, FLAG_SETENV)) {
381             if (ISSET(sudo_mode, MODE_PRESERVE_ENV))
382                 log_error(NO_MAIL,
383                     "sorry, you are not allowed to preserve the environment");
384             else
385                 validate_env_vars(sudo_user.env_vars);
386         }
387
388         log_auth(validated, 1);
389         if (sudo_mode == MODE_VALIDATE)
390             exit(0);
391         else if (sudo_mode == MODE_LIST) {
392             list_matches();
393 #ifdef HAVE_LDAP
394             sudo_ldap_list_matches();
395 #endif
396             exit(0);
397         }
398
399         /* Override user's umask if configured to do so. */
400         if (def_umask != 0777)
401             (void) umask(def_umask);
402
403         /* Restore coredumpsize resource limit. */
404 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
405         (void) setrlimit(RLIMIT_CORE, &corelimit);
406 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
407
408         /* Become specified user or root if executing a command. */
409         if (ISSET(sudo_mode, MODE_RUN))
410             set_perms(PERM_FULL_RUNAS);
411
412         /* Close the password and group files */
413         endpwent();
414         endgrent();
415
416         if (ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
417             char *p;
418
419             /* Convert /bin/sh -> -sh so shell knows it is a login shell */
420             if ((p = strrchr(NewArgv[0], '/')) == NULL)
421                 p = NewArgv[0];
422             *p = '-';
423             NewArgv[0] = p;
424
425             /* Change to target user's homedir. */
426             if (chdir(runas_pw->pw_dir) == -1)
427                 warn("unable to change directory to %s", runas_pw->pw_dir);
428         }
429
430         if (ISSET(sudo_mode, MODE_EDIT))
431             exit(sudo_edit(NewArgc, NewArgv, envp));
432
433         /* Insert user-specified environment variables. */
434         environ = insert_env_vars(environ, sudo_user.env_vars);
435
436         /* Restore signal handlers before we exec. */
437         (void) sigaction(SIGINT, &saved_sa_int, NULL);
438         (void) sigaction(SIGQUIT, &saved_sa_quit, NULL);
439         (void) sigaction(SIGTSTP, &saved_sa_tstp, NULL);
440         (void) sigaction(SIGCHLD, &saved_sa_chld, NULL);
441
442 #ifndef PROFILING
443         if (ISSET(sudo_mode, MODE_BACKGROUND) && fork() > 0)
444             exit(0);
445         else
446             execve(safe_cmnd, NewArgv, environ);
447 #else
448         exit(0);
449 #endif /* PROFILING */
450         /*
451          * If we got here then the exec() failed...
452          */
453         if (errno == ENOEXEC) {
454             NewArgv--;                  /* at least one extra slot... */
455             NewArgv[0] = "sh";
456             NewArgv[1] = safe_cmnd;
457             execve(_PATH_BSHELL, NewArgv, environ);
458         }
459         warn("unable to execute %s", safe_cmnd);
460         exit(127);
461     } else if (ISSET(validated, FLAG_NO_USER) || (validated & FLAG_NO_HOST)) {
462         log_auth(validated, 1);
463         exit(1);
464     } else if (ISSET(validated, VALIDATE_NOT_OK)) {
465         if (def_path_info) {
466             /*
467              * We'd like to not leak path info at all here, but that can
468              * *really* confuse the users.  To really close the leak we'd
469              * have to say "not allowed to run foo" even when the problem
470              * is just "no foo in path" since the user can trivially set
471              * their path to just contain a single dir.
472              */
473             log_auth(validated,
474                 !(cmnd_status == NOT_FOUND_DOT || cmnd_status == NOT_FOUND));
475             if (cmnd_status == NOT_FOUND)
476                 warnx("%s: command not found", user_cmnd);
477             else if (cmnd_status == NOT_FOUND_DOT)
478                 warnx("ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run.", user_cmnd, user_cmnd, user_cmnd);
479         } else {
480             /* Just tell the user they are not allowed to run foo. */
481             log_auth(validated, 1);
482         }
483         exit(1);
484     } else {
485         /* should never get here */
486         log_auth(validated, 1);
487         exit(1);
488     }
489     exit(0);    /* not reached */
490 }
491
492 /*
493  * Initialize timezone, set umask, fill in ``sudo_user'' struct and
494  * load the ``interfaces'' array.
495  */
496 static int
497 init_vars(sudo_mode, envp)
498     int sudo_mode;
499     char **envp;
500 {
501     char *p, **ep, thost[MAXHOSTNAMELEN];
502     int nohostname, rval;
503
504     /* Sanity check command from user. */
505     if (user_cmnd == NULL && strlen(NewArgv[0]) >= PATH_MAX)
506         errx(1, "%s: File name too long", NewArgv[0]);
507
508 #ifdef HAVE_TZSET
509     (void) tzset();             /* set the timezone if applicable */
510 #endif /* HAVE_TZSET */
511
512     /* Default value for cmnd and cwd, overridden later. */
513     if (user_cmnd == NULL)
514         user_cmnd = NewArgv[0];
515     (void) strlcpy(user_cwd, "unknown", sizeof(user_cwd));
516
517     /*
518      * We avoid gethostbyname() if possible since we don't want
519      * sudo to block if DNS or NIS is hosed.
520      * "host" is the (possibly fully-qualified) hostname and
521      * "shost" is the unqualified form of the hostname.
522      */
523     sudo_user.host_fqdn_queried = FALSE;
524     nohostname = gethostname(thost, sizeof(thost));
525     if (nohostname)
526         user_host = user_shost = "localhost";
527     else {
528         user_host = estrdup(thost);
529         if ((p = strchr(user_host, '.'))) {
530             *p = '\0';
531             user_shost = estrdup(user_host);
532             *p = '.';
533         } else {
534             user_shost = user_host;
535         }
536     }
537
538     if ((p = ttyname(STDIN_FILENO)) || (p = ttyname(STDOUT_FILENO))) {
539         user_tty = user_ttypath = estrdup(p);
540         if (strncmp(user_tty, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
541             user_tty += sizeof(_PATH_DEV) - 1;
542     } else
543         user_tty = "unknown";
544
545     for (ep = envp; *ep; ep++) {
546         switch (**ep) {
547             case 'P':
548                 if (strncmp("PATH=", *ep, 5) == 0)
549                     user_path = *ep + 5;
550                 break;
551             case 'S':
552                 if (strncmp("SHELL=", *ep, 6) == 0)
553                     user_shell = *ep + 6;
554                 else if (!user_prompt && strncmp("SUDO_PROMPT=", *ep, 12) == 0)
555                     user_prompt = *ep + 12;
556                 else if (strncmp("SUDO_USER=", *ep, 10) == 0)
557                     prev_user = *ep + 10;
558                 break;
559
560             }
561     }
562
563     /*
564      * Get a local copy of the user's struct passwd with the shadow password
565      * if necessary.  It is assumed that euid is 0 at this point so we
566      * can read the shadow passwd file if necessary.
567      */
568     if ((sudo_user.pw = sudo_getpwuid(getuid())) == NULL) {
569         /* Need to make a fake struct passwd for logging to work. */
570         struct passwd pw;
571         char pw_name[MAX_UID_T_LEN + 1];
572
573         pw.pw_uid = getuid();
574         (void) snprintf(pw_name, sizeof(pw_name), "%lu",
575             (unsigned long) pw.pw_uid);
576         pw.pw_name = pw_name;
577         sudo_user.pw = &pw;
578
579         /*
580          * If we are in -k/-K mode, just spew to stderr.  It is not unusual for
581          * users to place "sudo -k" in a .logout file which can cause sudo to
582          * be run during reboot after the YP/NIS/NIS+/LDAP/etc daemon has died.
583          */
584         if (sudo_mode & (MODE_INVALIDATE|MODE_KILL))
585             errx(1, "uid %s does not exist in the passwd file!", pw_name);
586         log_error(0, "uid %s does not exist in the passwd file!", pw_name);
587     }
588     if (user_shell == NULL || *user_shell == '\0')
589         user_shell = sudo_user.pw->pw_shell;
590
591     /* It is now safe to use log_error() and set_perms() */
592
593 #ifdef HAVE_GETGROUPS
594     if ((user_ngroups = getgroups(0, NULL)) > 0) {
595         user_groups = emalloc2(user_ngroups, sizeof(GETGROUPS_T));
596         if (getgroups(user_ngroups, user_groups) < 0)
597             log_error(USE_ERRNO|MSG_ONLY, "can't get group vector");
598     } else
599         user_ngroups = 0;
600 #endif
601
602     if (def_fqdn)
603         set_fqdn();                     /* may call log_error() */
604
605     if (nohostname)
606         log_error(USE_ERRNO|MSG_ONLY, "can't get hostname");
607
608     /* We don't query FQDN yet, it might get disabled later. Querying is done
609      * when host matching is executed and def_fqdn still true */
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                 case '-':
861                     NewArgc--;
862                     NewArgv++;
863                     goto args_done;
864                 case '\0':
865                     warnx("'-' requires an argument");
866                     usage(1);
867                 default:
868                     warnx("illegal option `%s'", NewArgv[0]);
869                     usage(1);
870             }
871         } else if (NewArgv[0][0] != '/' && strchr(NewArgv[0], '=') != NULL) {
872             /* Could be an environment variable. */
873             struct list_member *ev;
874             ev = emalloc(sizeof(*ev));
875             ev->value = NewArgv[0];
876             ev->next = sudo_user.env_vars;
877             sudo_user.env_vars = ev;
878         } else {
879             /* Not an arg */
880             break;
881         }
882         NewArgc--;
883         NewArgv++;
884     }
885 args_done:
886
887     if (ISSET(rval, MODE_EDIT) &&
888         (ISSET(rval, MODE_PRESERVE_ENV) || sudo_user.env_vars != NULL)) {
889         if (ISSET(rval, MODE_PRESERVE_ENV))
890             warnx("the `-E' option is not valid in edit mode");
891         if (sudo_user.env_vars != NULL)
892             warnx("you may not specify environment variables in edit mode");
893         usage(1);
894     }
895
896     if (user_runas != NULL && !ISSET(rval, (MODE_EDIT|MODE_RUN))) {
897         if (excl != '\0')
898             warnx("the `-u' and '-%c' options may not be used together", excl);
899         usage(1);
900     }
901     if ((NewArgc == 0 && (rval & MODE_EDIT)) ||
902         (NewArgc > 0 && !(rval & (MODE_RUN | MODE_EDIT))))
903         usage(1);
904     if (NewArgc == 0 && rval == MODE_RUN)
905         SET(rval, (MODE_IMPLIED_SHELL | MODE_SHELL));
906
907     return(rval);
908 }
909
910 /*
911  * Sanity check sudoers mode/owner/type.
912  * Leaves a file pointer to the sudoers file open in ``fp''.
913  */
914 static void
915 check_sudoers()
916 {
917     struct stat statbuf;
918     int rootstat, i;
919
920     /*
921      * Fix the mode and group on sudoers file from old default.
922      * Only works if file system is readable/writable by root.
923      */
924     if ((rootstat = stat_sudoers(_PATH_SUDOERS, &statbuf)) == 0 &&
925         SUDOERS_UID == statbuf.st_uid && SUDOERS_MODE != 0400 &&
926         (statbuf.st_mode & 0007777) == 0400) {
927
928         if (chmod(_PATH_SUDOERS, SUDOERS_MODE) == 0) {
929             warnx("fixed mode on %s", _PATH_SUDOERS);
930             SET(statbuf.st_mode, SUDOERS_MODE);
931             if (statbuf.st_gid != SUDOERS_GID) {
932                 if (!chown(_PATH_SUDOERS,(uid_t) -1,SUDOERS_GID)) {
933                     warnx("set group on %s", _PATH_SUDOERS);
934                     statbuf.st_gid = SUDOERS_GID;
935                 } else
936                     warn("unable to set group on %s", _PATH_SUDOERS);
937             }
938         } else
939             warn("unable to fix mode on %s", _PATH_SUDOERS);
940     }
941
942     /*
943      * Sanity checks on sudoers file.  Must be done as sudoers
944      * file owner.  We already did a stat as root, so use that
945      * data if we can't stat as sudoers file owner.
946      */
947     set_perms(PERM_SUDOERS);
948
949     if (rootstat != 0 && stat_sudoers(_PATH_SUDOERS, &statbuf) != 0)
950         log_error(USE_ERRNO, "can't stat %s", _PATH_SUDOERS);
951     else if (!S_ISREG(statbuf.st_mode))
952         log_error(0, "%s is not a regular file", _PATH_SUDOERS);
953     else if (statbuf.st_size == 0)
954         log_error(0, "%s is zero length", _PATH_SUDOERS);
955     else if ((statbuf.st_mode & 07777) != SUDOERS_MODE)
956         log_error(0, "%s is mode 0%o, should be 0%o", _PATH_SUDOERS,
957             (unsigned int) (statbuf.st_mode & 07777),
958             (unsigned int) SUDOERS_MODE);
959     else if (statbuf.st_uid != SUDOERS_UID)
960         log_error(0, "%s is owned by uid %lu, should be %lu", _PATH_SUDOERS,
961             (unsigned long) statbuf.st_uid, (unsigned long) SUDOERS_UID);
962     else if (statbuf.st_gid != SUDOERS_GID)
963         log_error(0, "%s is owned by gid %lu, should be %lu", _PATH_SUDOERS,
964             (unsigned long) statbuf.st_gid, (unsigned long) SUDOERS_GID);
965     else {
966         /* Solaris sometimes returns EAGAIN so try 10 times */
967         for (i = 0; i < 10 ; i++) {
968             errno = 0;
969             if ((sudoers_fp = fopen(_PATH_SUDOERS, "r")) == NULL ||
970                 fgetc(sudoers_fp) == EOF) {
971                 if (sudoers_fp != NULL)
972                     fclose(sudoers_fp);
973                 sudoers_fp = NULL;
974                 if (errno != EAGAIN && errno != EWOULDBLOCK)
975                     break;
976             } else
977                 break;
978             sleep(1);
979         }
980         if (sudoers_fp == NULL)
981             log_error(USE_ERRNO, "can't open %s", _PATH_SUDOERS);
982     }
983
984     set_perms(PERM_ROOT);               /* change back to root */
985 }
986
987 /*
988  * Close all open files (except std*) and turn off core dumps.
989  */
990 static void
991 initial_setup()
992 {
993     int miss[3], devnull = -1;
994 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
995     struct rlimit rl;
996
997     /*
998      * Turn off core dumps.
999      */
1000     (void) getrlimit(RLIMIT_CORE, &corelimit);
1001     memcpy(&rl, &corelimit, sizeof(struct rlimit));
1002     rl.rlim_cur = 0;
1003     (void) setrlimit(RLIMIT_CORE, &rl);
1004 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
1005
1006     /*
1007      * stdin, stdout and stderr must be open; set them to /dev/null
1008      * if they are closed and close all other fds.
1009      */
1010     miss[STDIN_FILENO] = fcntl(STDIN_FILENO, F_GETFL, 0) == -1;
1011     miss[STDOUT_FILENO] = fcntl(STDOUT_FILENO, F_GETFL, 0) == -1;
1012     miss[STDERR_FILENO] = fcntl(STDERR_FILENO, F_GETFL, 0) == -1;
1013     if (miss[STDIN_FILENO] || miss[STDOUT_FILENO] || miss[STDERR_FILENO]) {
1014         if ((devnull = open(_PATH_DEVNULL, O_RDWR, 0644)) != -1) {
1015             if (miss[STDIN_FILENO])
1016                 (void) dup2(devnull, STDIN_FILENO);
1017             if (miss[STDOUT_FILENO])
1018                 (void) dup2(devnull, STDOUT_FILENO);
1019             if (miss[STDERR_FILENO])
1020                 (void) dup2(devnull, STDERR_FILENO);
1021         }
1022     }
1023     closefrom(STDERR_FILENO + 1);
1024 }
1025
1026 #ifdef HAVE_LOGIN_CAP_H
1027 static void
1028 set_loginclass(pw)
1029     struct passwd *pw;
1030 {
1031     int errflags;
1032
1033     /*
1034      * Don't make it a fatal error if the user didn't specify the login
1035      * class themselves.  We do this because if login.conf gets
1036      * corrupted we want the admin to be able to use sudo to fix it.
1037      */
1038     if (login_class)
1039         errflags = NO_MAIL|MSG_ONLY;
1040     else
1041         errflags = NO_MAIL|MSG_ONLY|NO_EXIT;
1042
1043     if (login_class && strcmp(login_class, "-") != 0) {
1044         if (strcmp(*user_runas, "root") != 0 && user_uid != 0)
1045             errx(1, "only root can use -c %s", login_class);
1046     } else {
1047         login_class = pw->pw_class;
1048         if (!login_class || !*login_class)
1049             login_class =
1050                 (pw->pw_uid == 0) ? LOGIN_DEFROOTCLASS : LOGIN_DEFCLASS;
1051     }
1052
1053     lc = login_getclass(login_class);
1054     if (!lc || !lc->lc_class || strcmp(lc->lc_class, login_class) != 0) {
1055         log_error(errflags, "unknown login class: %s", login_class);
1056         if (!lc)
1057             lc = login_getclass(NULL);  /* needed for login_getstyle() later */
1058     }
1059 }
1060 #else
1061 static void
1062 set_loginclass(pw)
1063     struct passwd *pw;
1064 {
1065 }
1066 #endif /* HAVE_LOGIN_CAP_H */
1067
1068 #ifdef HAVE_PROJECT_H
1069 static void
1070 set_project(pw)
1071     struct passwd *pw;
1072 {
1073     int errflags = NO_MAIL|MSG_ONLY|NO_EXIT;
1074     int errval;
1075     struct project proj;
1076     struct project *resultp = '\0';
1077     char buf[1024];
1078
1079     /*
1080      * Collect the default project for the user and settaskid
1081      */
1082     setprojent();
1083     if (resultp = getdefaultproj(pw->pw_name, &proj, buf, sizeof(buf))) {
1084         errval = setproject(resultp->pj_name, pw->pw_name, TASK_NORMAL);
1085         if (errval != 0) {
1086             switch(errval) {
1087             case SETPROJ_ERR_TASK:
1088                 if (errno == EAGAIN)
1089                     log_error(errflags, "resource control limit has been reached");
1090                 else if (errno == ESRCH)
1091                     log_error(errflags, "user \"%s\" is not a member of "
1092                         "project \"%s\"", pw->pw_name, resultp->pj_name);
1093                 else if (errno == EACCES)
1094                     log_error(errflags, "the invoking task is final");
1095                 else
1096                     log_error(errflags, "could not join project \"%s\"",
1097                         resultp->pj_name);
1098                 break;
1099             case SETPROJ_ERR_POOL:
1100                 if (errno == EACCES)
1101                     log_error(errflags, "no resource pool accepting "
1102                             "default bindings exists for project \"%s\"",
1103                             resultp->pj_name);
1104                 else if (errno == ESRCH)
1105                     log_error(errflags, "specified resource pool does "
1106                             "not exist for project \"%s\"", resultp->pj_name);
1107                 else
1108                     log_error(errflags, "could not bind to default "
1109                             "resource pool for project \"%s\"", resultp->pj_name);
1110                 break;
1111             default:
1112                 if (errval <= 0) {
1113                     log_error(errflags, "setproject failed for project \"%s\"",
1114                         resultp->pj_name);
1115                 } else {
1116                     log_error(errflags, "warning, resource control assignment "
1117                         "failed for project \"%s\"", resultp->pj_name);
1118                 }
1119             }
1120         }
1121     } else {
1122         log_error(errflags, "getdefaultproj() error: %s", strerror(errno));
1123     }
1124     endprojent();
1125 }
1126 #else
1127 static void
1128 set_project(pw)
1129     struct passwd *pw;
1130 {
1131 }
1132 #endif /* HAVE_PROJECT_H */
1133
1134 /*
1135  * Look up the fully qualified domain name and set user_host and user_shost.
1136  */
1137 void
1138 set_fqdn()
1139 {
1140 #ifdef HAVE_GETADDRINFO
1141     struct addrinfo *res0, hint;
1142 #else
1143     struct hostent *hp;
1144 #endif
1145     char *p;
1146
1147 #ifdef HAVE_GETADDRINFO
1148     memset(&hint, 0, sizeof(hint));
1149     hint.ai_family = PF_UNSPEC;
1150     hint.ai_flags = AI_CANONNAME;
1151     if (getaddrinfo(user_host, NULL, &hint, &res0) != 0) {
1152 #else
1153     if (!(hp = gethostbyname(user_host))) {
1154 #endif
1155         log_error(MSG_ONLY|NO_EXIT,
1156             "unable to resolve host %s", user_host);
1157     } else {
1158         if (user_shost != user_host)
1159             efree(user_shost);
1160         efree(user_host);
1161 #ifdef HAVE_GETADDRINFO
1162         user_host = estrdup(res0->ai_canonname);
1163         freeaddrinfo(res0);
1164 #else
1165         user_host = estrdup(hp->h_name);
1166 #endif
1167     }
1168     if ((p = strchr(user_host, '.'))) {
1169         *p = '\0';
1170         user_shost = estrdup(user_host);
1171         *p = '.';
1172     } else {
1173         user_shost = user_host;
1174     }
1175     sudo_user.host_fqdn_queried = TRUE;
1176 }
1177
1178 /*
1179  * Get passwd entry for the user we are going to run commands as.
1180  * By default, this is "root".  Updates runas_pw as a side effect.
1181  */
1182 int
1183 set_runaspw(user)
1184     char *user;
1185 {
1186     if (runas_pw != NULL) {
1187         if (user_runas != &def_runas_default)
1188             return(TRUE);               /* don't override -u option */
1189         efree(runas_pw);
1190     }
1191     if (*user == '#') {
1192         runas_pw = sudo_getpwuid(atoi(user + 1));
1193         if (runas_pw == NULL) {
1194             runas_pw = emalloc(sizeof(struct passwd));
1195             (void) memset((VOID *)runas_pw, 0, sizeof(struct passwd));
1196             runas_pw->pw_uid = atoi(user + 1);
1197         }
1198     } else {
1199         runas_pw = sudo_getpwnam(user);
1200         if (runas_pw == NULL)
1201             log_error(NO_MAIL|MSG_ONLY, "no passwd entry for %s!", user);
1202     }
1203     return(TRUE);
1204 }
1205
1206 /*
1207  * Get passwd entry for the user we are going to authenticate as.
1208  * By default, this is the user invoking sudo.  In the most common
1209  * case, this matches sudo_user.pw or runas_pw.
1210  */
1211 static struct passwd *
1212 get_authpw()
1213 {
1214     struct passwd *pw;
1215
1216     if (def_rootpw) {
1217         if (runas_pw->pw_uid == 0)
1218             pw = runas_pw;
1219         else if ((pw = sudo_getpwuid(0)) == NULL)
1220             log_error(0, "uid 0 does not exist in the passwd file!");
1221     } else if (def_runaspw) {
1222         if (strcmp(def_runas_default, *user_runas) == 0)
1223             pw = runas_pw;
1224         else if ((pw = sudo_getpwnam(def_runas_default)) == NULL)
1225             log_error(0, "user %s does not exist in the passwd file!",
1226                 def_runas_default);
1227     } else if (def_targetpw) {
1228         if (runas_pw->pw_name == NULL)
1229             log_error(NO_MAIL|MSG_ONLY, "no passwd entry for %lu!",
1230                 (unsigned long) runas_pw->pw_uid);
1231         pw = runas_pw;
1232     } else
1233         pw = sudo_user.pw;
1234
1235     return(pw);
1236 }
1237
1238 /*
1239  * Tell which options are mutually exclusive and exit.
1240  */
1241 static void
1242 usage_excl(exit_val)
1243     int exit_val;
1244 {
1245     warnx("Only one of the -e, -h, i, -k, -K, -l, -s, -v or -V options may be used");
1246     usage(exit_val);
1247 }
1248
1249 /*
1250  * Give usage message and exit.
1251  */
1252 static void
1253 usage(exit_val)
1254     int exit_val;
1255 {
1256     char **p, **uvec[4];
1257     int i, linelen, linemax, ulen, plen;
1258     static char *uvec1[] = {
1259         " -h |",
1260         " -K |",
1261         " -k |",
1262         " -L |",
1263         " -l |",
1264         " -V |",
1265         " -v",
1266         NULL
1267     };
1268     static char *uvec2[] = {
1269         " [-bEHPS]",
1270 #ifdef HAVE_BSD_AUTH_H
1271         " [-a auth_type]",
1272 #endif
1273 #ifdef HAVE_LOGIN_CAP_H
1274         " [-c class|-]",
1275 #endif
1276         " [-p prompt]",
1277         " [-u username|#uid]",
1278         " [VAR=value]",
1279         " {-i | -s | <command>}",
1280         NULL
1281     };
1282     static char *uvec3[] = {
1283         " -e",
1284         " [-S]",
1285 #ifdef HAVE_BSD_AUTH_H
1286         " [-a auth_type]",
1287 #endif
1288 #ifdef HAVE_LOGIN_CAP_H
1289         " [-c class|-]",
1290 #endif
1291         " [-p prompt]",
1292         " [-u username|#uid]",
1293         " file ...",
1294         NULL
1295     };
1296
1297     /*
1298      * Use usage vectors appropriate to the progname.
1299      */
1300     if (strcmp(getprogname(), "sudoedit") == 0) {
1301         uvec[0] = uvec3 + 1;
1302         uvec[1] = NULL;
1303     } else {
1304         uvec[0] = uvec1;
1305         uvec[1] = uvec2;
1306         uvec[2] = uvec3;
1307         uvec[3] = NULL;
1308     }
1309
1310     /*
1311      * Print usage and wrap lines as needed.
1312      * Assumes an 80-character wide terminal, which is kind of bogus...
1313      */
1314     ulen = (int)strlen(getprogname()) + 7;
1315     linemax = 80;
1316     for (i = 0; uvec[i] != NULL; i++) {
1317         printf("usage: %s", getprogname());
1318         linelen = linemax - ulen;
1319         for (p = uvec[i]; *p != NULL; p++) {
1320             plen = (int)strlen(*p);
1321             if (linelen >= plen || linelen == linemax - ulen) {
1322                 fputs(*p, stdout);
1323                 linelen -= plen;
1324             } else {
1325                 p--;
1326                 linelen = linemax - ulen;
1327                 printf("\n%*s", ulen, "");
1328             }
1329         }
1330         putchar('\n');
1331     }
1332     exit(exit_val);
1333 }