2 * Copyright (c) 1993-1996,1998-2004 Todd C. Miller <Todd.Miller@courtesan.com>
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.
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.
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.
20 * For a brief history of sudo, please see the HISTORY file included
21 * with this distribution.
32 #include <sys/types.h>
34 #include <sys/param.h>
35 #include <sys/socket.h>
37 # include <sys/time.h>
38 # include <sys/resource.h>
48 #endif /* STDC_HEADERS */
50 # if defined(HAVE_MEMORY_H) && !defined(STDC_HEADERS)
55 # ifdef HAVE_STRINGS_H
58 #endif /* HAVE_STRING_H */
61 #endif /* HAVE_UNISTD_H */
65 # include "emul/err.h"
66 #endif /* HAVE_ERR_H */
73 #include <netinet/in.h>
75 #if defined(HAVE_GETPRPWNAM) && defined(HAVE_SET_AUTH_PARAMETERS)
78 # include <hpsecurity.h>
80 # include <sys/security.h>
83 #endif /* HAVE_GETPRPWNAM && HAVE_SET_AUTH_PARAMETERS */
84 #ifdef HAVE_LOGIN_CAP_H
85 # include <login_cap.h>
86 # ifndef LOGIN_DEFROOTCLASS
87 # define LOGIN_DEFROOTCLASS "daemon"
92 #include "interfaces.h"
96 static const char rcsid[] = "$Sudo: sudo.c,v 1.370 2004/08/24 18:01:13 millert Exp $";
102 static int init_vars __P((int));
103 static int parse_args __P((int, char **));
104 static void check_sudoers __P((void));
105 static void initial_setup __P((void));
106 static void set_loginclass __P((struct passwd *));
107 static void usage __P((int));
108 static void usage_excl __P((int));
109 static struct passwd *get_authpw __P((void));
110 extern int sudo_edit __P((int, char **));
111 extern void list_matches __P((void));
112 extern char **rebuild_env __P((char **, int, int));
113 extern char **zero_env __P((char **));
114 extern struct passwd *sudo_getpwnam __P((const char *));
115 extern struct passwd *sudo_getpwuid __P((uid_t));
116 extern struct passwd *sudo_pwdup __P((const struct passwd *));
122 char **Argv, **NewArgv;
124 struct sudo_user sudo_user;
125 struct passwd *auth_pw;
127 struct interface *interfaces;
131 extern int errorlineno;
132 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
133 static struct rlimit corelimit;
134 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
135 #ifdef HAVE_LOGIN_CAP_H
137 #endif /* HAVE_LOGIN_CAP_H */
138 #ifdef HAVE_BSD_AUTH_H
140 #endif /* HAVE_BSD_AUTH_H */
141 sigaction_t saved_sa_int, saved_sa_quit, saved_sa_tstp, saved_sa_chld;
142 void (*set_perms) __P((int));
146 main(argc, argv, envp)
158 extern int printmatches;
159 extern char **environ;
162 if ((Argc = argc) < 1)
165 /* Must be done as the first thing... */
166 #if defined(HAVE_GETPRPWNAM) && defined(HAVE_SET_AUTH_PARAMETERS)
167 (void) set_auth_parameters(Argc, Argv);
168 # ifdef HAVE_INITPRIVS
171 #endif /* HAVE_GETPRPWNAM && HAVE_SET_AUTH_PARAMETERS */
173 /* Zero out the environment. */
174 environ = zero_env(envp);
177 errx(1, "must be setuid root");
181 * Ignore keyboard-generated signals so the user cannot interrupt
182 * us at some point and avoid the logging.
183 * Install handler to wait for children when they exit.
185 sigemptyset(&sa.sa_mask);
186 sa.sa_flags = SA_RESTART;
187 sa.sa_handler = SIG_IGN;
188 (void) sigaction(SIGINT, &sa, &saved_sa_int);
189 (void) sigaction(SIGQUIT, &sa, &saved_sa_quit);
190 (void) sigaction(SIGTSTP, &sa, &saved_sa_tstp);
191 sa.sa_handler = reapchild;
192 (void) sigaction(SIGCHLD, &sa, &saved_sa_chld);
195 * Turn off core dumps, close open files and setup set_perms().
200 /* Parse our arguments. */
201 sudo_mode = parse_args(Argc, Argv);
203 /* Setup defaults data structures. */
206 /* Load the list of local ip addresses and netmasks. */
210 if (ISSET(sudo_mode, MODE_SHELL))
212 else if (ISSET(sudo_mode, MODE_EDIT))
213 user_cmnd = "sudoedit";
217 (void) printf("Sudo version %s\n", version);
230 user_cmnd = "validate";
234 case MODE_INVALIDATE:
249 /* Must have a command to run... */
250 if (user_cmnd == NULL && NewArgc == 0)
253 cmnd_status = init_vars(sudo_mode);
256 validated = sudo_ldap_check(pwflag);
258 /* Skip reading /etc/sudoers if LDAP told us to */
259 if (def_ignore_local_sudoers); /* skips */
260 else if (ISSET(validated, VALIDATE_OK) && !printmatches); /* skips */
261 else if (ISSET(validated, VALIDATE_OK) && printmatches)
263 check_sudoers(); /* check mode/owner on _PATH_SUDOERS */
265 /* User is found in LDAP and we want a list of all sudo commands the
266 * user can do, so consult sudoers but throw away result.
268 sudoers_lookup(pwflag);
273 check_sudoers(); /* check mode/owner on _PATH_SUDOERS */
275 /* Validate the user but don't search for pseudo-commands. */
276 validated = sudoers_lookup(pwflag);
278 if (safe_cmnd == NULL)
279 safe_cmnd = user_cmnd;
282 * If we are using set_perms_posix() and the stay_setuid flag was not set,
283 * set the real, effective and saved uids to 0 and use set_perms_nosuid()
284 * instead of set_perms_posix().
286 #if !defined(HAVE_SETRESUID) && !defined(HAVE_SETREUID) && \
287 !defined(NO_SAVED_IDS) && defined(_SC_SAVED_IDS) && defined(_SC_VERSION)
288 if (!def_stay_setuid && set_perms == set_perms_posix) {
293 set_perms = set_perms_nosuid;
298 * Look up the timestamp dir owner if one is specified.
300 if (def_timestampowner) {
303 if (*def_timestampowner == '#')
304 pw = getpwuid(atoi(def_timestampowner + 1));
306 pw = getpwnam(def_timestampowner);
308 log_error(0, "timestamp owner (%s): No such user",
310 timestamp_uid = pw->pw_uid;
313 /* This goes after the sudoers parse since we honor sudoers options. */
314 if (sudo_mode == MODE_KILL || sudo_mode == MODE_INVALIDATE) {
315 remove_timestamp((sudo_mode == MODE_KILL));
319 if (ISSET(validated, VALIDATE_ERROR))
320 log_error(0, "parse error in %s near line %d", _PATH_SUDOERS,
323 /* Is root even allowed to run sudo? */
324 if (user_uid == 0 && !def_root_sudo) {
325 (void) fprintf(stderr,
326 "Sorry, %s has been configured to not allow root to run it.\n",
331 /* If given the -P option, set the "preserve_groups" flag. */
332 if (ISSET(sudo_mode, MODE_PRESERVE_GROUPS))
333 def_preserve_groups = TRUE;
335 /* If no command line args and "set_home" is not set, error out. */
336 if (ISSET(sudo_mode, MODE_IMPLIED_SHELL) && !def_shell_noargs)
339 /* May need to set $HOME to target user if we are running a command. */
340 if (ISSET(sudo_mode, MODE_RUN) && (def_always_set_home ||
341 (ISSET(sudo_mode, MODE_SHELL) && def_set_home)))
342 SET(sudo_mode, MODE_RESET_HOME);
344 /* Bail if a tty is required and we don't have one. */
345 if (def_requiretty) {
346 if ((fd = open(_PATH_TTY, O_RDWR|O_NOCTTY)) == -1)
347 log_error(NO_MAIL, "sorry, you must have a tty to run sudo");
352 /* Fill in passwd struct based on user we are authenticating as. */
353 auth_pw = get_authpw();
355 /* Require a password if sudoers says so. */
356 if (!ISSET(validated, FLAG_NOPASS))
357 check_user(ISSET(validated, FLAG_CHECK_USER));
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) {
363 if ((pw = sudo_getpwnam(prev_user)) != NULL) {
369 /* Build a new environment that avoids any nasty bits if we have a cmnd. */
370 if (ISSET(sudo_mode, MODE_RUN))
371 new_environ = rebuild_env(envp, sudo_mode, ISSET(validated, FLAG_NOEXEC));
375 if (ISSET(validated, VALIDATE_OK)) {
376 /* Finally tell the user if the command did not exist. */
377 if (cmnd_status == NOT_FOUND_DOT) {
378 warnx("ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run.", user_cmnd, user_cmnd, user_cmnd);
380 } else if (cmnd_status == NOT_FOUND) {
381 warnx("%s: command not found", user_cmnd);
385 log_auth(validated, 1);
386 if (sudo_mode == MODE_VALIDATE)
388 else if (sudo_mode == MODE_LIST) {
391 sudo_ldap_list_matches();
396 /* Override user's umask if configured to do so. */
397 if (def_umask != 0777)
398 (void) umask(def_umask);
400 /* Restore coredumpsize resource limit. */
401 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
402 (void) setrlimit(RLIMIT_CORE, &corelimit);
403 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
405 /* Become specified user or root if executing a command. */
406 if (ISSET(sudo_mode, MODE_RUN))
407 set_perms(PERM_FULL_RUNAS);
409 /* Close the password and group files */
413 /* Install the real environment. */
414 environ = new_environ;
416 if (ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
419 /* Convert /bin/sh -> -sh so shell knows it is a login shell */
420 if ((p = strrchr(NewArgv[0], '/')) == NULL)
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);
430 if (ISSET(sudo_mode, MODE_EDIT))
431 exit(sudo_edit(NewArgc, NewArgv));
433 /* Restore signal handlers before we exec. */
434 (void) sigaction(SIGINT, &saved_sa_int, NULL);
435 (void) sigaction(SIGQUIT, &saved_sa_quit, NULL);
436 (void) sigaction(SIGTSTP, &saved_sa_tstp, NULL);
437 (void) sigaction(SIGCHLD, &saved_sa_chld, NULL);
440 if (ISSET(sudo_mode, MODE_BACKGROUND) && fork() > 0)
443 EXECV(safe_cmnd, NewArgv); /* run the command */
446 #endif /* PROFILING */
448 * If we got here then the exec() failed...
450 warn("unable to execute %s", safe_cmnd);
452 } else if (ISSET(validated, FLAG_NO_USER) || (validated & FLAG_NO_HOST)) {
453 log_auth(validated, 1);
455 } else if (ISSET(validated, VALIDATE_NOT_OK)) {
458 * We'd like to not leak path info at all here, but that can
459 * *really* confuse the users. To really close the leak we'd
460 * have to say "not allowed to run foo" even when the problem
461 * is just "no foo in path" since the user can trivially set
462 * their path to just contain a single dir.
465 !(cmnd_status == NOT_FOUND_DOT || cmnd_status == NOT_FOUND));
466 if (cmnd_status == NOT_FOUND)
467 warnx("%s: command not found", user_cmnd);
468 else if (cmnd_status == NOT_FOUND_DOT)
469 warnx("ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run.", user_cmnd, user_cmnd, user_cmnd);
471 /* Just tell the user they are not allowed to run foo. */
472 log_auth(validated, 1);
476 /* should never get here */
477 log_auth(validated, 1);
480 exit(0); /* not reached */
484 * Initialize timezone, set umask, fill in ``sudo_user'' struct and
485 * load the ``interfaces'' array.
491 char *p, thost[MAXHOSTNAMELEN];
492 int nohostname, rval;
494 /* Sanity check command from user. */
495 if (user_cmnd == NULL && strlen(NewArgv[0]) >= PATH_MAX)
496 errx(1, "%s: File name too long", NewArgv[0]);
499 (void) tzset(); /* set the timezone if applicable */
500 #endif /* HAVE_TZSET */
502 /* Default value for cmnd and cwd, overridden later. */
503 if (user_cmnd == NULL)
504 user_cmnd = NewArgv[0];
505 (void) strlcpy(user_cwd, "unknown", sizeof(user_cwd));
508 * We avoid gethostbyname() if possible since we don't want
509 * sudo to block if DNS or NIS is hosed.
510 * "host" is the (possibly fully-qualified) hostname and
511 * "shost" is the unqualified form of the hostname.
513 nohostname = gethostname(thost, sizeof(thost));
515 user_host = user_shost = "localhost";
517 user_host = estrdup(thost);
519 /* Defer call to set_fqdn() until log_error() is safe. */
520 user_shost = user_host;
522 if ((p = strchr(user_host, '.'))) {
524 user_shost = estrdup(user_host);
527 user_shost = user_host;
532 if ((p = ttyname(STDIN_FILENO)) || (p = ttyname(STDOUT_FILENO))) {
533 if (strncmp(p, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
534 p += sizeof(_PATH_DEV) - 1;
535 user_tty = estrdup(p);
537 user_tty = "unknown";
540 * Get a local copy of the user's struct passwd with the shadow password
541 * if necessary. It is assumed that euid is 0 at this point so we
542 * can read the shadow passwd file if necessary.
544 if ((sudo_user.pw = sudo_getpwuid(getuid())) == NULL) {
545 /* Need to make a fake struct passwd for logging to work. */
547 char pw_name[MAX_UID_T_LEN + 1];
549 pw.pw_uid = getuid();
550 (void) snprintf(pw_name, sizeof(pw_name), "%lu",
551 (unsigned long) pw.pw_uid);
552 pw.pw_name = pw_name;
556 * If we are in -k/-K mode, just spew to stderr. It is not unusual for
557 * users to place "sudo -k" in a .logout file which can cause sudo to
558 * be run during reboot after the YP/NIS/NIS+/LDAP/etc daemon has died.
560 if (sudo_mode & (MODE_INVALIDATE|MODE_KILL))
561 errx(1, "uid %s does not exist in the passwd file!", pw_name);
562 log_error(0, "uid %s does not exist in the passwd file!", pw_name);
564 if (user_shell == NULL || *user_shell == '\0')
565 user_shell = sudo_user.pw->pw_shell;
567 /* It is now safe to use log_error() and set_perms() */
570 set_fqdn(); /* may call log_error() */
573 log_error(USE_ERRNO|MSG_ONLY, "can't get hostname");
575 set_runaspw(*user_runas); /* may call log_error() */
576 if (*user_runas[0] == '#' && runas_pw->pw_name && runas_pw->pw_name[0])
577 *user_runas = estrdup(runas_pw->pw_name);
580 * Get current working directory. Try as user, fall back to root.
582 set_perms(PERM_USER);
583 if (!getcwd(user_cwd, sizeof(user_cwd))) {
584 set_perms(PERM_ROOT);
585 if (!getcwd(user_cwd, sizeof(user_cwd))) {
586 warnx("cannot get working directory");
587 (void) strlcpy(user_cwd, "unknown", sizeof(user_cwd));
590 set_perms(PERM_ROOT);
593 * If we were given the '-e', '-i' or '-s' options we need to redo
594 * NewArgv and NewArgc.
596 if ((sudo_mode & (MODE_SHELL | MODE_EDIT))) {
597 char **dst, **src = NewArgv;
599 NewArgv = (char **) emalloc2((++NewArgc + 1), sizeof(char *));
600 if (ISSET(sudo_mode, MODE_EDIT))
601 NewArgv[0] = "sudoedit";
602 else if (ISSET(sudo_mode, MODE_LOGIN_SHELL))
603 NewArgv[0] = runas_pw->pw_shell;
604 else if (user_shell && *user_shell)
605 NewArgv[0] = user_shell;
607 errx(1, "unable to determine shell");
609 /* copy the args from NewArgv */
610 for (dst = NewArgv + 1; (*dst = *src) != NULL; ++src, ++dst)
614 /* Set login class if applicable. */
615 set_loginclass(sudo_user.pw);
617 /* Resolve the path and return. */
619 user_stat = emalloc(sizeof(struct stat));
620 if (sudo_mode & (MODE_RUN | MODE_EDIT)) {
621 if (ISSET(sudo_mode, MODE_RUN)) {
622 /* XXX - default_runas may be modified during parsing of sudoers */
623 set_perms(PERM_RUNAS);
624 rval = find_path(NewArgv[0], &user_cmnd, user_stat, user_path);
625 set_perms(PERM_ROOT);
627 /* Failed as root, try as invoking user. */
628 set_perms(PERM_USER);
629 rval = find_path(NewArgv[0], &user_cmnd, user_stat, user_path);
630 set_perms(PERM_ROOT);
639 /* If we didn't realloc NewArgv it is contiguous so just count. */
640 if (!(sudo_mode & (MODE_SHELL | MODE_EDIT))) {
641 size = (size_t) (NewArgv[NewArgc-1] - NewArgv[1]) +
642 strlen(NewArgv[NewArgc-1]) + 1;
644 for (size = 0, from = NewArgv + 1; *from; from++)
645 size += strlen(*from) + 1;
648 /* Alloc and build up user_args. */
649 user_args = (char *) emalloc(size);
650 for (to = user_args, from = NewArgv + 1; *from; from++) {
651 n = strlcpy(to, *from, size - (to - user_args));
652 if (n >= size - (to - user_args))
653 errx(1, "internal error, init_vars() overflow");
660 if ((user_base = strrchr(user_cmnd, '/')) != NULL)
663 user_base = user_cmnd;
669 * Command line argument parsing, can't use getopt(3).
672 parse_args(argc, argv)
676 int rval = MODE_RUN; /* what mode is sudo to be run in? */
677 int excl = 0; /* exclusive arg, no others allowed */
682 /* First, check to see if we were invoked as "sudoedit". */
683 if (strcmp(getprogname(), "sudoedit") == 0) {
689 if (NewArgc == 0 && rval == MODE_RUN) { /* no options and no command */
690 SET(rval, (MODE_IMPLIED_SHELL | MODE_SHELL));
694 while (NewArgc > 0 && NewArgv[0][0] == '-') {
695 if (NewArgv[0][1] != '\0' && NewArgv[0][2] != '\0')
696 warnx("please use single character options");
698 switch (NewArgv[0][1]) {
700 /* Must have an associated prompt. */
701 if (NewArgv[1] == NULL)
704 user_prompt = NewArgv[1];
710 /* Must have an associated runas user. */
711 if (NewArgv[1] == NULL)
714 user_runas = &NewArgv[1];
719 #ifdef HAVE_BSD_AUTH_H
721 /* Must have an associated authentication style. */
722 if (NewArgv[1] == NULL)
725 login_style = NewArgv[1];
731 #ifdef HAVE_LOGIN_CAP_H
733 /* Must have an associated login class. */
734 if (NewArgv[1] == NULL)
737 login_class = NewArgv[1];
738 def_use_loginclass = TRUE;
745 SET(rval, MODE_BACKGROUND);
749 if (excl && excl != 'e')
754 rval = MODE_VALIDATE;
755 if (excl && excl != 'v')
760 SET(rval, (MODE_LOGIN_SHELL | MODE_SHELL));
761 def_env_reset = TRUE;
762 if (excl && excl != 'i')
767 rval = MODE_INVALIDATE;
768 if (excl && excl != 'k')
774 if (excl && excl != 'K')
779 rval = MODE_LISTDEFS;
780 if (excl && excl != 'L')
786 if (excl && excl != 'l')
792 if (excl && excl != 'V')
798 if (excl && excl != 'h')
803 SET(rval, MODE_SHELL);
804 if (excl && excl != 's')
809 SET(rval, MODE_RESET_HOME);
812 SET(rval, MODE_PRESERVE_GROUPS);
815 SET(tgetpass_flags, TGP_STDIN);
820 if (rval == MODE_RUN)
821 SET(rval, (MODE_IMPLIED_SHELL | MODE_SHELL));
824 warnx("'-' requires an argument");
827 warnx("illegal option `%s'", NewArgv[0]);
834 if (user_runas != NULL && !ISSET(rval, (MODE_EDIT|MODE_RUN))) {
836 warnx("the `-u' and '-%c' options may not be used together", excl);
840 if ((NewArgc == 0 && (rval & MODE_EDIT)) ||
841 (NewArgc > 0 && !(rval & (MODE_RUN | MODE_EDIT))))
848 * Sanity check sudoers mode/owner/type.
849 * Leaves a file pointer to the sudoers file open in ``fp''.
859 * Fix the mode and group on sudoers file from old default.
860 * Only works if file system is readable/writable by root.
862 if ((rootstat = stat_sudoers(_PATH_SUDOERS, &statbuf)) == 0 &&
863 SUDOERS_UID == statbuf.st_uid && SUDOERS_MODE != 0400 &&
864 (statbuf.st_mode & 0007777) == 0400) {
866 if (chmod(_PATH_SUDOERS, SUDOERS_MODE) == 0) {
867 warnx("fixed mode on %s", _PATH_SUDOERS);
868 SET(statbuf.st_mode, SUDOERS_MODE);
869 if (statbuf.st_gid != SUDOERS_GID) {
870 if (!chown(_PATH_SUDOERS,(uid_t) -1,SUDOERS_GID)) {
871 warnx("set group on %s", _PATH_SUDOERS);
872 statbuf.st_gid = SUDOERS_GID;
874 warn("unable to set group on %s", _PATH_SUDOERS);
877 warn("unable to fix mode on %s", _PATH_SUDOERS);
881 * Sanity checks on sudoers file. Must be done as sudoers
882 * file owner. We already did a stat as root, so use that
883 * data if we can't stat as sudoers file owner.
885 set_perms(PERM_SUDOERS);
887 if (rootstat != 0 && stat_sudoers(_PATH_SUDOERS, &statbuf) != 0)
888 log_error(USE_ERRNO, "can't stat %s", _PATH_SUDOERS);
889 else if (!S_ISREG(statbuf.st_mode))
890 log_error(0, "%s is not a regular file", _PATH_SUDOERS);
891 else if (statbuf.st_size == 0)
892 log_error(0, "%s is zero length", _PATH_SUDOERS);
893 else if ((statbuf.st_mode & 07777) != SUDOERS_MODE)
894 log_error(0, "%s is mode 0%o, should be 0%o", _PATH_SUDOERS,
895 (statbuf.st_mode & 07777), SUDOERS_MODE);
896 else if (statbuf.st_uid != SUDOERS_UID)
897 log_error(0, "%s is owned by uid %lu, should be %lu", _PATH_SUDOERS,
898 (unsigned long) statbuf.st_uid, (unsigned long) SUDOERS_UID);
899 else if (statbuf.st_gid != SUDOERS_GID)
900 log_error(0, "%s is owned by gid %lu, should be %lu", _PATH_SUDOERS,
901 (unsigned long) statbuf.st_gid, (unsigned long) SUDOERS_GID);
903 /* Solaris sometimes returns EAGAIN so try 10 times */
904 for (i = 0; i < 10 ; i++) {
906 if ((sudoers_fp = fopen(_PATH_SUDOERS, "r")) == NULL ||
907 fread(&c, sizeof(c), 1, sudoers_fp) != 1) {
909 if (errno != EAGAIN && errno != EWOULDBLOCK)
915 if (sudoers_fp == NULL)
916 log_error(USE_ERRNO, "can't open %s", _PATH_SUDOERS);
919 set_perms(PERM_ROOT); /* change back to root */
923 * Close all open files (except std*) and turn off core dumps.
924 * Also sets the set_perms() pointer to the correct function.
929 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
933 * Turn off core dumps.
935 (void) getrlimit(RLIMIT_CORE, &corelimit);
936 memcpy(&rl, &corelimit, sizeof(struct rlimit));
938 (void) setrlimit(RLIMIT_CORE, &rl);
939 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
941 closefrom(STDERR_FILENO + 1);
944 * Make set_perms point to the correct function.
945 * If we are using setresuid() or setreuid() we only need to set this
946 * once. If we are using POSIX saved uids we will switch to
947 * set_perms_nosuid after sudoers has been parsed if the "stay_suid"
950 #if defined(HAVE_SETRESUID) || defined(HAVE_SETREUID)
951 set_perms = set_perms_suid;
953 # if !defined(NO_SAVED_IDS) && defined(_SC_SAVED_IDS) && defined(_SC_VERSION)
954 if (sysconf(_SC_SAVED_IDS) == 1 && sysconf(_SC_VERSION) >= 199009)
955 set_perms = set_perms_posix;
958 set_perms = set_perms_nosuid;
959 #endif /* HAVE_SETRESUID || HAVE_SETREUID */
962 #ifdef HAVE_LOGIN_CAP_H
970 * Don't make it a fatal error if the user didn't specify the login
971 * class themselves. We do this because if login.conf gets
972 * corrupted we want the admin to be able to use sudo to fix it.
975 errflags = NO_MAIL|MSG_ONLY;
977 errflags = NO_MAIL|MSG_ONLY|NO_EXIT;
979 if (login_class && strcmp(login_class, "-") != 0) {
980 if (strcmp(*user_runas, "root") != 0 && user_uid != 0)
981 errx(1, "only root can use -c %s", login_class);
983 login_class = pw->pw_class;
984 if (!login_class || !*login_class)
986 (pw->pw_uid == 0) ? LOGIN_DEFROOTCLASS : LOGIN_DEFCLASS;
989 lc = login_getclass(login_class);
990 if (!lc || !lc->lc_class || strcmp(lc->lc_class, login_class) != 0) {
991 log_error(errflags, "unknown login class: %s", login_class);
993 lc = login_getclass(NULL); /* needed for login_getstyle() later */
1002 #endif /* HAVE_LOGIN_CAP_H */
1005 * Look up the fully qualified domain name and set user_host and user_shost.
1013 if (!(hp = gethostbyname(user_host))) {
1014 log_error(MSG_ONLY|NO_EXIT,
1015 "unable to lookup %s via gethostbyname()", user_host);
1017 if (user_shost != user_host)
1020 user_host = estrdup(hp->h_name);
1022 if ((p = strchr(user_host, '.'))) {
1024 user_shost = estrdup(user_host);
1027 user_shost = user_host;
1032 * Get passwd entry for the user we are going to run commands as.
1033 * By default, this is "root". Updates runas_pw as a side effect.
1039 if (runas_pw != NULL) {
1040 if (user_runas != &def_runas_default)
1041 return(TRUE); /* don't override -u option */
1045 runas_pw = sudo_getpwuid(atoi(user + 1));
1046 if (runas_pw == NULL) {
1047 runas_pw = emalloc(sizeof(struct passwd));
1048 (void) memset((VOID *)runas_pw, 0, sizeof(struct passwd));
1049 runas_pw->pw_uid = atoi(user + 1);
1052 runas_pw = sudo_getpwnam(user);
1053 if (runas_pw == NULL)
1054 log_error(NO_MAIL|MSG_ONLY, "no passwd entry for %s!", user);
1060 * Get passwd entry for the user we are going to authenticate as.
1061 * By default, this is the user invoking sudo. In the most common
1062 * case, this matches sudo_user.pw or runas_pw.
1064 static struct passwd *
1070 if (runas_pw->pw_uid == 0)
1072 else if ((pw = sudo_getpwuid(0)) == NULL)
1073 log_error(0, "uid 0 does not exist in the passwd file!");
1074 } else if (def_runaspw) {
1075 if (strcmp(def_runas_default, *user_runas) == 0)
1077 else if ((pw = sudo_getpwnam(def_runas_default)) == NULL)
1078 log_error(0, "user %s does not exist in the passwd file!",
1080 } else if (def_targetpw) {
1081 if (runas_pw->pw_name == NULL)
1082 log_error(NO_MAIL|MSG_ONLY, "no passwd entry for %lu!",
1083 (unsigned long) runas_pw->pw_uid);
1092 * Tell which options are mutually exclusive and exit.
1095 usage_excl(exit_val)
1098 warnx("Only one of the -e, -h, -k, -K, -l, -s, -v or -V options may be used");
1103 * Give usage message and exit.
1110 int linelen, linemax, ulen;
1111 static char *uvec[] = {
1113 #ifdef HAVE_BSD_AUTH_H
1116 #ifdef HAVE_LOGIN_CAP_H
1120 " [-u username|#uid]",
1121 " { -e file [...] | -i | -s | <command> }",
1126 * For sudoedit, replace the last entry in the usage vector.
1127 * For sudo, print the secondary usage.
1129 if (strcmp(getprogname(), "sudoedit") == 0) {
1130 /* Replace the last entry in the usage vector. */
1131 for (p = uvec; p[1] != NULL; p++)
1135 fprintf(stderr, "usage: %s -K | -L | -V | -h | -k | -l | -v\n",
1140 * Print the main usage and wrap lines as needed.
1141 * Assumes an 80-character wide terminal, which is kind of bogus...
1143 ulen = (int)strlen(getprogname()) + 7;
1145 linelen = linemax - ulen;
1146 printf("usage: %s", getprogname());
1147 for (p = uvec; *p != NULL; p++) {
1148 if (linelen == linemax || (linelen -= strlen(*p)) >= 0) {
1153 printf("\n%*s", ulen, "");