Imported Debian patch 1.6.6-1.3woody1
[debian/sudo] / sudo.c
1 /*
2  * Copyright (c) 1993-1996,1998-2002 Todd C. Miller <Todd.Miller@courtesan.com>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * 3. The name of the author may not be used to endorse or promote products
17  *    derived from this software without specific prior written permission.
18  *
19  * 4. Products derived from this software may not be called "Sudo" nor
20  *    may "Sudo" appear in their names without specific prior written
21  *    permission from the author.
22  *
23  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
24  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
25  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
26  * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
27  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
28  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
29  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
30  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
31  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
32  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  *
34  * For a brief history of sudo, please see the HISTORY file included
35  * with this distribution.
36  */
37
38 #define _SUDO_SUDO_C
39
40 #include "config.h"
41
42 #include <sys/types.h>
43 #include <sys/stat.h>
44 #include <sys/param.h>
45 #include <sys/socket.h>
46 #ifdef HAVE_SETRLIMIT
47 # include <sys/time.h>
48 # include <sys/resource.h>
49 #endif
50 #include <stdio.h>
51 #ifdef STDC_HEADERS
52 # include <stdlib.h>
53 # include <stddef.h>
54 #else
55 # ifdef HAVE_STDLIB_H
56 #  include <stdlib.h>
57 # endif
58 #endif /* STDC_HEADERS */
59 #ifdef HAVE_STRING_H
60 # if defined(HAVE_MEMORY_H) && !defined(STDC_HEADERS)
61 #  include <memory.h>
62 # endif
63 # include <string.h>
64 #else
65 # ifdef HAVE_STRINGS_H
66 #  include <strings.h>
67 # endif
68 #endif /* HAVE_STRING_H */
69 #ifdef HAVE_UNISTD_H
70 # include <unistd.h>
71 #endif /* HAVE_UNISTD_H */
72 #include <pwd.h>
73 #include <errno.h>
74 #include <fcntl.h>
75 #include <signal.h>
76 #include <grp.h>
77 #include <time.h>
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
96 #include "sudo.h"
97 #include "interfaces.h"
98 #include "version.h"
99
100 #ifndef lint
101 static const char rcsid[] = "$Sudo: sudo.c,v 1.318 2002/01/15 23:43:59 millert Exp $";
102 #endif /* lint */
103
104 /*
105  * Prototypes
106  */
107 static int init_vars                    __P((int));
108 static int parse_args                   __P((void));
109 static void check_sudoers               __P((void));
110 static void initial_setup               __P((void));
111 static void set_loginclass              __P((struct passwd *));
112 static void usage                       __P((int));
113 static void usage_excl                  __P((int));
114 static struct passwd *get_authpw        __P((void));
115 extern void list_matches                __P((void));
116 extern char **rebuild_env               __P((int, char **));
117 extern char **zero_env                  __P((char **));
118 extern struct passwd *sudo_getpwnam     __P((const char *));
119 extern struct passwd *sudo_getpwuid     __P((uid_t));
120
121 /*
122  * Globals
123  */
124 int Argc;
125 char **Argv;
126 int NewArgc = 0;
127 char **NewArgv = NULL;
128 struct sudo_user sudo_user;
129 struct passwd *auth_pw;
130 FILE *sudoers_fp = NULL;
131 struct interface *interfaces;
132 int num_interfaces;
133 int tgetpass_flags;
134 extern int errorlineno;
135 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
136 static struct rlimit corelimit;
137 #endif /* RLIMIT_CORE */
138 #ifdef HAVE_LOGIN_CAP_H
139 login_cap_t *lc;
140 #endif /* HAVE_LOGIN_CAP_H */
141 #ifdef HAVE_BSD_AUTH_H
142 char *login_style;
143 #endif /* HAVE_BSD_AUTH_H */
144 void (*set_perms) __P((int, int));
145
146
147 int
148 main(argc, argv, envp)
149     int argc;
150     char **argv;
151     char **envp;
152 {
153     int validated;
154     int fd;
155     int cmnd_status;
156     int sudo_mode;
157     int pwflag;
158     char **new_environ;
159     sigaction_t sa;
160     extern int printmatches;
161     extern char **environ;
162
163     /* Must be done as the first thing... */
164 #if defined(HAVE_GETPRPWNAM) && defined(HAVE_SET_AUTH_PARAMETERS)
165     (void) set_auth_parameters(argc, argv);
166 # ifdef HAVE_INITPRIVS
167     initprivs();
168 # endif
169 #endif /* HAVE_GETPRPWNAM && HAVE_SET_AUTH_PARAMETERS */
170
171     /* Zero out the environment. */
172     environ = zero_env(envp);
173
174     Argv = argv;
175     Argc = argc;
176
177     if (geteuid() != 0) {
178         (void) fprintf(stderr, "Sorry, %s must be setuid root.\n", Argv[0]);
179         exit(1);
180     }
181
182     /*
183      * Ignore keyboard-generated signals so the user cannot interrupt
184      * us at some point and avoid the logging.
185      */
186     sigemptyset(&sa.sa_mask);
187     sa.sa_flags = SA_RESTART;
188     sa.sa_handler = SIG_IGN;
189     (void) sigaction(SIGINT, &sa, NULL);
190     (void) sigaction(SIGQUIT, &sa, NULL);
191     (void) sigaction(SIGTSTP, &sa, NULL);
192
193     /*
194      * Setup signal handlers, turn off core dumps, and close open files.
195      */
196     initial_setup();
197     setpwent();
198
199     /* Parse our arguments. */
200     sudo_mode = parse_args();
201
202     /* Setup defaults data structures. */
203     init_defaults();
204
205     /* Load the list of local ip addresses and netmasks.  */
206     load_interfaces();
207
208     pwflag = 0;
209     if (sudo_mode & MODE_SHELL)
210         user_cmnd = "shell";
211     else
212         switch (sudo_mode) {
213             case MODE_VERSION:
214                 (void) printf("Sudo version %s\n", version);
215                 if (getuid() == 0) {
216                     putchar('\n');
217                     dump_auth_methods();
218                     dump_defaults();
219                     dump_interfaces();
220                     dump_badenv();
221                 }
222                 exit(0);
223                 break;
224             case MODE_HELP:
225                 usage(0);
226                 break;
227             case MODE_VALIDATE:
228                 user_cmnd = "validate";
229                 pwflag = I_VERIFYPW_I;
230                 break;
231             case MODE_KILL:
232             case MODE_INVALIDATE:
233                 user_cmnd = "kill";
234                 pwflag = -1;
235                 break;
236             case MODE_LISTDEFS:
237                 list_options();
238                 exit(0);
239                 break;
240             case MODE_LIST:
241                 user_cmnd = "list";
242                 pwflag = I_LISTPW_I;
243                 printmatches = 1;
244                 break;
245         }
246
247     /* Must have a command to run... */
248     if (user_cmnd == NULL && NewArgc == 0)
249         usage(1);
250
251     cmnd_status = init_vars(sudo_mode);
252
253     check_sudoers();    /* check mode/owner on _PATH_SUDOERS */
254
255     /* Validate the user but don't search for pseudo-commands. */
256     validated = sudoers_lookup(pwflag);
257
258     /*
259      * If we have POSIX saved uids and the stay_setuid flag was not set,
260      * set the real, effective and saved uids to 0 and use set_perms_fallback()
261      * instead of set_perms_posix().
262      */
263 #if !defined(NO_SAVED_IDS) && defined(_SC_SAVED_IDS) && defined(_SC_VERSION)
264     if (!def_flag(I_STAY_SETUID) && set_perms == set_perms_posix) {
265         if (setuid(0)) {
266             perror("setuid(0)");
267             exit(1);
268         }
269         set_perms = set_perms_fallback;
270     }
271 #endif
272
273     /*
274      * Look up runas user passwd struct.  If we are given a uid then
275      * there may be no corresponding passwd(5) entry (which is OK).
276      */
277     if (**user_runas == '#') {
278         runas_pw = sudo_getpwuid(atoi(*user_runas + 1));
279         if (runas_pw == NULL) {
280             runas_pw = emalloc(sizeof(struct passwd));
281             (void) memset((VOID *)runas_pw, 0, sizeof(struct passwd));
282             runas_pw->pw_uid = atoi(*user_runas + 1);
283         }
284     } else {
285         runas_pw = sudo_getpwnam(*user_runas);
286         if (runas_pw == NULL)
287             log_error(NO_MAIL|MSG_ONLY, "no passwd entry for %s!", *user_runas);
288     }
289     if (safe_cmnd == NULL)
290         safe_cmnd = user_cmnd;
291
292     /* This goes after the sudoers parse since we honor sudoers options. */
293     if (sudo_mode == MODE_KILL || sudo_mode == MODE_INVALIDATE) {
294         remove_timestamp((sudo_mode == MODE_KILL));
295         exit(0);
296     }
297
298     if (validated & VALIDATE_ERROR)
299         log_error(0, "parse error in %s near line %d", _PATH_SUDOERS,
300             errorlineno);
301
302     /* Is root even allowed to run sudo? */
303     if (user_uid == 0 && !def_flag(I_ROOT_SUDO)) {
304         (void) fputs("You are already root, you don't need to use sudo.\n",
305             stderr);
306         exit(1);
307     }
308
309     /* If given the -P option, set the "preserve_groups" flag. */
310     if (sudo_mode & MODE_PRESERVE_GROUPS)
311         def_flag(I_PRESERVE_GROUPS) = TRUE;
312
313     /* If no command line args and "set_home" is not set, error out. */
314     if ((sudo_mode & MODE_IMPLIED_SHELL) && !def_flag(I_SHELL_NOARGS))
315         usage(1);
316
317     /* May need to set $HOME to target user if we are running a command. */
318     if ((sudo_mode & MODE_RUN) && (def_flag(I_ALWAYS_SET_HOME) ||
319         ((sudo_mode & MODE_SHELL) && def_flag(I_SET_HOME))))
320         sudo_mode |= MODE_RESET_HOME;
321
322     /* Bail if a tty is required and we don't have one.  */
323     if (def_flag(I_REQUIRETTY)) {
324         if ((fd = open(_PATH_TTY, O_RDWR|O_NOCTTY)) == -1)
325             log_error(NO_MAIL, "sorry, you must have a tty to run sudo");
326         else
327             (void) close(fd);
328     }
329
330     /* Fill in passwd struct based on user we are authenticating as.  */
331     auth_pw = get_authpw();
332
333     /* Require a password unless the NOPASS tag was set.  */
334     if (!(validated & FLAG_NOPASS))
335         check_user();
336
337     /* Build up custom environment that avoids any nasty bits. */
338     new_environ = rebuild_env(sudo_mode, envp);
339
340     if (validated & VALIDATE_OK) {
341         /* Finally tell the user if the command did not exist. */
342         if (cmnd_status == NOT_FOUND_DOT) {
343             (void) fprintf(stderr, "%s: ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run.\n", Argv[0], user_cmnd, user_cmnd, user_cmnd);
344             exit(1);
345         } else if (cmnd_status == NOT_FOUND) {
346             (void) fprintf(stderr, "%s: %s: command not found\n", Argv[0],
347                 user_cmnd);
348             exit(1);
349         }
350
351         log_auth(validated, 1);
352         if (sudo_mode == MODE_VALIDATE)
353             exit(0);
354         else if (sudo_mode == MODE_LIST) {
355             list_matches();
356             exit(0);
357         }
358
359         /* Reset signal handlers before we exec. */
360         sigemptyset(&sa.sa_mask);
361         sa.sa_flags = SA_RESTART;
362         sa.sa_handler = SIG_DFL;
363         (void) sigaction(SIGINT, &sa, NULL);
364         (void) sigaction(SIGQUIT, &sa, NULL);
365         (void) sigaction(SIGTSTP, &sa, NULL);
366
367         /* Override user's umask if configured to do so. */
368         if (def_ival(I_UMASK) != 0777)
369             (void) umask(def_mode(I_UMASK));
370
371         /* Restore coredumpsize resource limit. */
372 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
373         (void) setrlimit(RLIMIT_CORE, &corelimit);
374 #endif /* RLIMIT_CORE */
375
376         /* Become specified user or root. */
377         set_perms(PERM_RUNAS, sudo_mode);
378
379         /* Close the password and group files */
380         endpwent();
381         endgrent();
382
383         /* Install the new environment. */
384         environ = new_environ;
385
386 #ifndef PROFILING
387         if ((sudo_mode & MODE_BACKGROUND) && fork() > 0)
388             exit(0);
389         else
390             EXEC(safe_cmnd, NewArgv);   /* run the command */
391 #else
392         exit(0);
393 #endif /* PROFILING */
394         /*
395          * If we got here then the exec() failed...
396          */
397         (void) fprintf(stderr, "%s: unable to exec %s: %s\n",
398             Argv[0], safe_cmnd, strerror(errno));
399         exit(127);
400     } else if ((validated & FLAG_NO_USER) || (validated & FLAG_NO_HOST)) {
401         log_auth(validated, 1);
402         exit(1);
403     } else if (validated & VALIDATE_NOT_OK) {
404         if (def_flag(I_PATH_INFO)) {
405             /*
406              * We'd like to not leak path info at all here, but that can
407              * *really* confuse the users.  To really close the leak we'd
408              * have to say "not allowed to run foo" even when the problem
409              * is just "no foo in path" since the user can trivially set
410              * their path to just contain a single dir.
411              */
412             log_auth(validated,
413                 !(cmnd_status == NOT_FOUND_DOT || cmnd_status == NOT_FOUND));
414             if (cmnd_status == NOT_FOUND)
415                 (void) fprintf(stderr, "%s: %s: command not found\n", Argv[0],
416                     user_cmnd);
417             else if (cmnd_status == NOT_FOUND_DOT)
418                 (void) fprintf(stderr, "%s: ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run.\n", Argv[0], user_cmnd, user_cmnd, user_cmnd);
419         } else {
420             /* Just tell the user they are not allowed to run foo. */
421             log_auth(validated, 1);
422         }
423         exit(1);
424     } else {
425         /* should never get here */
426         log_auth(validated, 1);
427         exit(1);
428     }
429     exit(0);    /* not reached */
430 }
431
432 /*
433  * Initialize timezone, set umask, fill in ``sudo_user'' struct and
434  * load the ``interfaces'' array.
435  */
436 static int
437 init_vars(sudo_mode)
438     int sudo_mode;
439 {
440     char *p, thost[MAXHOSTNAMELEN];
441     int nohostname, rval;
442
443     /* Sanity check command from user. */
444     if (user_cmnd == NULL && strlen(NewArgv[0]) >= MAXPATHLEN) {
445         (void) fprintf(stderr, "%s: %s: Pathname too long\n", Argv[0],
446             NewArgv[0]);
447         exit(1);
448     }
449
450 #ifdef HAVE_TZSET
451     (void) tzset();             /* set the timezone if applicable */
452 #endif /* HAVE_TZSET */
453
454     /* Default value for cmnd and cwd, overridden later. */
455     if (user_cmnd == NULL)
456         user_cmnd = NewArgv[0];
457     (void) strcpy(user_cwd, "unknown");
458
459     /*
460      * We avoid gethostbyname() if possible since we don't want
461      * sudo to block if DNS or NIS is hosed.
462      * "host" is the (possibly fully-qualified) hostname and
463      * "shost" is the unqualified form of the hostname.
464      */
465     nohostname = gethostname(thost, sizeof(thost));
466     if (nohostname)
467         user_host = user_shost = "localhost";
468     else {
469         user_host = estrdup(thost);
470         if (def_flag(I_FQDN)) {
471             /* Defer call to set_fqdn() until log_error() is safe. */
472             user_shost = user_host;
473         } else {
474             if ((p = strchr(user_host, '.'))) {
475                 *p = '\0';
476                 user_shost = estrdup(user_host);
477                 *p = '.';
478             } else {
479                 user_shost = user_host;
480             }
481         }
482     }
483
484     if ((p = ttyname(STDIN_FILENO)) || (p = ttyname(STDOUT_FILENO))) {
485         if (strncmp(p, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
486             p += sizeof(_PATH_DEV) - 1;
487         user_tty = estrdup(p);
488     } else
489         user_tty = "unknown";
490
491     /*
492      * Get a local copy of the user's struct passwd with the shadow password
493      * if necessary.  It is assumed that euid is 0 at this point so we
494      * can read the shadow passwd file if necessary.
495      */
496     if ((sudo_user.pw = sudo_getpwuid(getuid())) == NULL) {
497         /* Need to make a fake struct passwd for logging to work. */
498         struct passwd pw;
499         char pw_name[MAX_UID_T_LEN + 1];
500
501         pw.pw_uid = getuid();
502         (void) sprintf(pw_name, "%ld", (long) pw.pw_uid);
503         pw.pw_name = pw_name;
504         sudo_user.pw = &pw;
505
506         log_error(0, "uid %ld does not exist in the passwd file!",
507             (long) pw.pw_uid);
508     }
509     if (user_shell == NULL || *user_shell == '\0')
510         user_shell = sudo_user.pw->pw_shell;
511
512     /* It is now safe to use log_error() and set_perms() */
513
514     /*
515      * Must defer set_fqdn() until it is safe to call log_error()
516      */
517     if (def_flag(I_FQDN))
518         set_fqdn();
519
520     if (nohostname)
521         log_error(USE_ERRNO|MSG_ONLY, "can't get hostname");
522
523     /*
524      * Get current working directory.  Try as user, fall back to root.
525      */
526     set_perms(PERM_USER, sudo_mode);
527     if (!getcwd(user_cwd, sizeof(user_cwd))) {
528         set_perms(PERM_ROOT, sudo_mode);
529         if (!getcwd(user_cwd, sizeof(user_cwd))) {
530             (void) fprintf(stderr, "%s: Can't get working directory!\n",
531                            Argv[0]);
532             (void) strcpy(user_cwd, "unknown");
533         }
534     } else
535         set_perms(PERM_ROOT, sudo_mode);
536
537     /*
538      * If we were given the '-s' option (run shell) we need to redo
539      * NewArgv and NewArgc.
540      */
541     if ((sudo_mode & MODE_SHELL)) {
542         char **dst, **src = NewArgv;
543
544         NewArgv = (char **) emalloc (sizeof(char *) * (++NewArgc + 1));
545         if (user_shell && *user_shell) {
546             NewArgv[0] = user_shell;
547         } else {
548             (void) fprintf(stderr, "%s: Unable to determine shell.", Argv[0]);
549             exit(1);
550         }
551
552         /* copy the args from Argv */
553         for (dst = NewArgv + 1; (*dst = *src) != NULL; ++src, ++dst)
554             ;
555     }
556
557     /* Set login class if applicable. */
558     set_loginclass(sudo_user.pw);
559
560     /* Resolve the path and return. */
561     if ((sudo_mode & MODE_RUN)) {
562         /* XXX - should call this as runas user, not root. */
563         rval = find_path(NewArgv[0], &user_cmnd, user_path);
564         if (rval != FOUND) {
565             /* Failed as root, try as invoking user. */
566             set_perms(PERM_USER, sudo_mode);
567             rval = find_path(NewArgv[0], &user_cmnd, user_path);
568             set_perms(PERM_ROOT, sudo_mode);
569         }
570
571         /* set user_args */
572         if (NewArgc > 1) {
573             char *to, **from;
574             size_t size;
575
576             /* If MODE_SHELL not set then NewArgv is contiguous so just count */
577             if (!(sudo_mode & MODE_SHELL)) {
578                 size = (size_t) (NewArgv[NewArgc-1] - NewArgv[1]) +
579                         strlen(NewArgv[NewArgc-1]) + 1;
580             } else {
581                 for (size = 0, from = NewArgv + 1; *from; from++)
582                     size += strlen(*from) + 1;
583             }
584
585             /* alloc and copy. */
586             to = user_args = (char *) emalloc(size);
587             for (from = NewArgv + 1; *from; from++) {
588                 (void) strcpy(to, *from);
589                 to += strlen(*from);
590                 *to++ = ' ';
591             }
592             *--to = '\0';
593         }
594     } else
595         rval = FOUND;
596
597     return(rval);
598 }
599
600 /*
601  * Command line argument parsing, can't use getopt(3).
602  */
603 static int
604 parse_args()
605 {
606     int rval = MODE_RUN;                /* what mode is suod to be run in? */
607     int excl = 0;                       /* exclusive arg, no others allowed */
608
609     NewArgv = Argv + 1;
610     NewArgc = Argc - 1;
611
612     if (NewArgc == 0) {                 /* no options and no command */
613         rval |= (MODE_IMPLIED_SHELL | MODE_SHELL);
614         return(rval);
615     }
616
617     while (NewArgc > 0 && NewArgv[0][0] == '-') {
618         if (NewArgv[0][1] != '\0' && NewArgv[0][2] != '\0') {
619             (void) fprintf(stderr, "%s: Please use single character options\n",
620                 Argv[0]);
621             usage(1);
622         }
623
624         switch (NewArgv[0][1]) {
625             case 'p':
626                 /* Must have an associated prompt. */
627                 if (NewArgv[1] == NULL)
628                     usage(1);
629
630                 user_prompt = NewArgv[1];
631
632                 /* Shift Argv over and adjust Argc. */
633                 NewArgc--;
634                 NewArgv++;
635                 break;
636             case 'u':
637                 /* Must have an associated runas user. */
638                 if (NewArgv[1] == NULL)
639                     usage(1);
640
641                 user_runas = &NewArgv[1];
642
643                 /* Shift Argv over and adjust Argc. */
644                 NewArgc--;
645                 NewArgv++;
646                 break;
647 #ifdef HAVE_BSD_AUTH_H
648             case 'a':
649                 /* Must have an associated authentication style. */
650                 if (NewArgv[1] == NULL)
651                     usage(1);
652
653                 login_style = NewArgv[1];
654
655                 /* Shift Argv over and adjust Argc. */
656                 NewArgc--;
657                 NewArgv++;
658                 break;
659 #endif
660 #ifdef HAVE_LOGIN_CAP_H
661             case 'c':
662                 /* Must have an associated login class. */
663                 if (NewArgv[1] == NULL)
664                     usage(1);
665
666                 login_class = NewArgv[1];
667                 def_flag(I_USE_LOGINCLASS) = TRUE;
668
669                 /* Shift Argv over and adjust Argc. */
670                 NewArgc--;
671                 NewArgv++;
672                 break;
673 #endif
674             case 'b':
675                 rval |= MODE_BACKGROUND;
676                 break;
677             case 'v':
678                 rval = MODE_VALIDATE;
679                 if (excl && excl != 'v')
680                     usage_excl(1);
681                 excl = 'v';
682                 break;
683             case 'k':
684                 rval = MODE_INVALIDATE;
685                 if (excl && excl != 'k')
686                     usage_excl(1);
687                 excl = 'k';
688                 break;
689             case 'K':
690                 rval = MODE_KILL;
691                 if (excl && excl != 'K')
692                     usage_excl(1);
693                 excl = 'K';
694                 break;
695             case 'L':
696                 rval = MODE_LISTDEFS;
697                 if (excl && excl != 'L')
698                     usage_excl(1);
699                 excl = 'L';
700                 break;
701             case 'l':
702                 rval = MODE_LIST;
703                 if (excl && excl != 'l')
704                     usage_excl(1);
705                 excl = 'l';
706                 break;
707             case 'V':
708                 rval = MODE_VERSION;
709                 if (excl && excl != 'V')
710                     usage_excl(1);
711                 excl = 'V';
712                 break;
713             case 'h':
714                 rval = MODE_HELP;
715                 if (excl && excl != 'h')
716                     usage_excl(1);
717                 excl = 'h';
718                 break;
719             case 's':
720                 rval |= MODE_SHELL;
721                 if (excl && excl != 's')
722                     usage_excl(1);
723                 excl = 's';
724                 break;
725             case 'H':
726                 rval |= MODE_RESET_HOME;
727                 break;
728             case 'P':
729                 rval |= MODE_PRESERVE_GROUPS;
730                 break;
731             case 'S':
732                 tgetpass_flags |= TGP_STDIN;
733                 break;
734             case '-':
735                 NewArgc--;
736                 NewArgv++;
737                 if (rval == MODE_RUN)
738                     rval |= (MODE_IMPLIED_SHELL | MODE_SHELL);
739                 return(rval);
740             case '\0':
741                 (void) fprintf(stderr, "%s: '-' requires an argument\n",
742                     Argv[0]);
743                 usage(1);
744             default:
745                 (void) fprintf(stderr, "%s: Illegal option %s\n", Argv[0],
746                     NewArgv[0]);
747                 usage(1);
748         }
749         NewArgc--;
750         NewArgv++;
751     }
752
753     if (NewArgc > 0 && !(rval & MODE_RUN))
754         usage(1);
755
756     return(rval);
757 }
758
759 /*
760  * Sanity check sudoers mode/owner/type.
761  * Leaves a file pointer to the sudoers file open in ``fp''.
762  */
763 static void
764 check_sudoers()
765 {
766     struct stat statbuf;
767     int rootstat, i;
768     char c;
769
770     /*
771      * Fix the mode and group on sudoers file from old default.
772      * Only works if filesystem is readable/writable by root.
773      */
774     if ((rootstat = lstat(_PATH_SUDOERS, &statbuf)) == 0 &&
775         SUDOERS_UID == statbuf.st_uid && SUDOERS_MODE != 0400 &&
776         (statbuf.st_mode & 0007777) == 0400) {
777
778         if (chmod(_PATH_SUDOERS, SUDOERS_MODE) == 0) {
779             (void) fprintf(stderr, "%s: fixed mode on %s\n",
780                 Argv[0], _PATH_SUDOERS);
781             statbuf.st_mode |= SUDOERS_MODE;
782             if (statbuf.st_gid != SUDOERS_GID) {
783                 if (!chown(_PATH_SUDOERS,(uid_t) -1,SUDOERS_GID)) {
784                     (void) fprintf(stderr, "%s: set group on %s\n",
785                         Argv[0], _PATH_SUDOERS);
786                     statbuf.st_gid = SUDOERS_GID;
787                 } else {
788                     (void) fprintf(stderr,"%s: Unable to set group on %s: %s\n",
789                         Argv[0], _PATH_SUDOERS, strerror(errno));
790                 }
791             }
792         } else {
793             (void) fprintf(stderr, "%s: Unable to fix mode on %s: %s\n",
794                 Argv[0], _PATH_SUDOERS, strerror(errno));
795         }
796     }
797
798     /*
799      * Sanity checks on sudoers file.  Must be done as sudoers
800      * file owner.  We already did a stat as root, so use that
801      * data if we can't stat as sudoers file owner.
802      */
803     set_perms(PERM_SUDOERS, 0);
804
805     if (rootstat != 0 && lstat(_PATH_SUDOERS, &statbuf) != 0)
806         log_error(USE_ERRNO, "can't stat %s", _PATH_SUDOERS);
807     else if (!S_ISREG(statbuf.st_mode))
808         log_error(0, "%s is not a regular file", _PATH_SUDOERS);
809     else if (statbuf.st_size == 0)
810         log_error(0, "%s is zero length", _PATH_SUDOERS);
811     else if ((statbuf.st_mode & 07777) != SUDOERS_MODE)
812         log_error(0, "%s is mode 0%o, should be 0%o", _PATH_SUDOERS,
813             (statbuf.st_mode & 07777), SUDOERS_MODE);
814     else if (statbuf.st_uid != SUDOERS_UID)
815         log_error(0, "%s is owned by uid %ld, should be %d", _PATH_SUDOERS,
816             (long) statbuf.st_uid, SUDOERS_UID);
817     else if (statbuf.st_gid != SUDOERS_GID)
818         log_error(0, "%s is owned by gid %ld, should be %d", _PATH_SUDOERS,
819             (long) statbuf.st_gid, SUDOERS_GID);
820     else {
821         /* Solaris sometimes returns EAGAIN so try 10 times */
822         for (i = 0; i < 10 ; i++) {
823             errno = 0;
824             if ((sudoers_fp = fopen(_PATH_SUDOERS, "r")) == NULL ||
825                 fread(&c, sizeof(c), 1, sudoers_fp) != 1) {
826                 sudoers_fp = NULL;
827                 if (errno != EAGAIN && errno != EWOULDBLOCK)
828                     break;
829             } else
830                 break;
831             sleep(1);
832         }
833         if (sudoers_fp == NULL)
834             log_error(USE_ERRNO, "can't open %s", _PATH_SUDOERS);
835     }
836
837     set_perms(PERM_ROOT, 0);            /* change back to root */
838 }
839
840 /*
841  * Close all open files (except std*) and turn off core dumps.
842  * Also sets the set_perms() pointer to the correct function.
843  */
844 static void
845 initial_setup()
846 {
847     int fd, maxfd;
848 #ifdef HAVE_SETRLIMIT
849     struct rlimit rl;
850 #endif
851     sigaction_t sa;
852
853 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
854     /*
855      * Turn off core dumps.
856      */
857     (void) getrlimit(RLIMIT_CORE, &corelimit);
858     rl.rlim_cur = rl.rlim_max = 0;
859     (void) setrlimit(RLIMIT_CORE, &rl);
860 #endif /* RLIMIT_CORE */
861
862     /*
863      * Close any open fd's other than stdin, stdout and stderr.
864      */
865 #ifdef HAVE_SYSCONF
866     maxfd = sysconf(_SC_OPEN_MAX) - 1;
867 #else
868     maxfd = getdtablesize() - 1;
869 #endif /* HAVE_SYSCONF */
870 #ifdef RLIMIT_NOFILE
871     if (getrlimit(RLIMIT_NOFILE, &rl) == 0) {
872         if (rl.rlim_max != RLIM_INFINITY && rl.rlim_max <= maxfd)
873             maxfd = rl.rlim_max - 1;
874     }
875 #endif /* RLIMIT_NOFILE */
876
877     for (fd = maxfd; fd > STDERR_FILENO; fd--)
878         (void) close(fd);
879
880     /* Catch children as they die... */
881     sigemptyset(&sa.sa_mask);
882     sa.sa_flags = SA_RESTART;
883     sa.sa_handler = reapchild;
884     (void) sigaction(SIGCHLD, &sa, NULL);
885
886     /* Set set_perms pointer to the correct function */
887 #if !defined(NO_SAVED_IDS) && defined(_SC_SAVED_IDS) && defined(_SC_VERSION)
888     if (sysconf(_SC_SAVED_IDS) == 1 && sysconf(_SC_VERSION) >= 199009)
889         set_perms = set_perms_posix;
890     else
891 #endif
892         set_perms = set_perms_fallback;
893 }
894
895 #ifdef HAVE_LOGIN_CAP_H
896 static void
897 set_loginclass(pw)
898     struct passwd *pw;
899 {
900     int errflags;
901
902     /*
903      * Don't make it a fatal error if the user didn't specify the login
904      * class themselves.  We do this because if login.conf gets
905      * corrupted we want the admin to be able to use sudo to fix it.
906      */
907     if (login_class)
908         errflags = NO_MAIL|MSG_ONLY;
909     else
910         errflags = NO_MAIL|MSG_ONLY|NO_EXIT;
911
912     if (login_class && strcmp(login_class, "-") != 0) {
913         if (strcmp(*user_runas, "root") != 0 && user_uid != 0) {
914             (void) fprintf(stderr, "%s: only root can use -c %s\n",
915                 Argv[0], login_class);
916             exit(1);
917         }
918     } else {
919         login_class = pw->pw_class;
920         if (!login_class || !*login_class)
921             login_class =
922                 (pw->pw_uid == 0) ? LOGIN_DEFROOTCLASS : LOGIN_DEFCLASS;
923     }
924
925     lc = login_getclass(login_class);
926     if (!lc || !lc->lc_class || strcmp(lc->lc_class, login_class) != 0) {
927         log_error(errflags, "unknown login class: %s", login_class);
928         if (!lc)
929             lc = login_getclass(NULL);  /* needed for login_getstyle() later */
930     }
931 }
932 #else
933 static void
934 set_loginclass(pw)
935     struct passwd *pw;
936 {
937 }
938 #endif /* HAVE_LOGIN_CAP_H */
939
940 /*
941  * Look up the fully qualified domain name and set user_host and user_shost.
942  */
943 void
944 set_fqdn()
945 {
946     struct hostent *hp;
947     char *p;
948
949     if (!(hp = gethostbyname(user_host))) {
950         log_error(MSG_ONLY|NO_EXIT,
951             "unable to lookup %s via gethostbyname()", user_host);
952     } else {
953         if (user_shost != user_host)
954             free(user_shost);
955         free(user_host);
956         user_host = estrdup(hp->h_name);
957     }
958     if ((p = strchr(user_host, '.'))) {
959         *p = '\0';
960         user_shost = estrdup(user_host);
961         *p = '.';
962     } else {
963         user_shost = user_host;
964     }
965 }
966
967 /*
968  * Get passwd entry for the user we are going to authenticate as.
969  * By default, this is the user invoking sudo...
970  */
971 static struct passwd *
972 get_authpw()
973 {
974     struct passwd *pw;
975
976     if (def_ival(I_ROOTPW)) {
977         if ((pw = sudo_getpwuid(0)) == NULL)
978             log_error(0, "uid 0 does not exist in the passwd file!");
979     } else if (def_ival(I_RUNASPW)) {
980         if ((pw = sudo_getpwnam(def_str(I_RUNAS_DEFAULT))) == NULL)
981             log_error(0, "user %s does not exist in the passwd file!",
982                 def_str(I_RUNAS_DEFAULT));
983     } else if (def_ival(I_TARGETPW)) {
984         if (**user_runas == '#') {
985             if ((pw = sudo_getpwuid(atoi(*user_runas + 1))) == NULL)
986                 log_error(0, "uid %s does not exist in the passwd file!",
987                     user_runas);
988         } else {
989             if ((pw = sudo_getpwnam(*user_runas)) == NULL)
990                 log_error(0, "user %s does not exist in the passwd file!",
991                     user_runas);
992         }
993     } else
994         pw = sudo_user.pw;
995
996     return(pw);
997 }
998
999 /*
1000  * Tell which options are mutually exclusive and exit.
1001  */
1002 static void
1003 usage_excl(exit_val)
1004     int exit_val;
1005 {
1006     (void) fprintf(stderr,
1007         "Only one of the -h, -k, -K, -l, -s, -v or -V options may be used\n");
1008     usage(exit_val);
1009 }
1010
1011 /*
1012  * Give usage message and exit.
1013  */
1014 static void
1015 usage(exit_val)
1016     int exit_val;
1017 {
1018
1019     (void) fprintf(stderr, "usage: sudo -V | -h | -L | -l | -v | -k | -K | %s",
1020         "[-H] [-P] [-S] [-b] [-p prompt]\n            [-u username/#uid] ");
1021 #ifdef HAVE_LOGIN_CAP_H
1022     (void) fprintf(stderr, "[-c class] ");
1023 #endif
1024 #ifdef HAVE_BSD_AUTH_H
1025     (void) fprintf(stderr, "[-a auth_type] ");
1026 #endif
1027     (void) fprintf(stderr, "-s | <command>\n");
1028     exit(exit_val);
1029 }