2 * Copyright (c) 1993-1996,1998-2007 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 */
72 #if TIME_WITH_SYS_TIME
78 #include <netinet/in.h>
80 #if defined(HAVE_GETPRPWNAM) && defined(HAVE_SET_AUTH_PARAMETERS)
83 # include <hpsecurity.h>
85 # include <sys/security.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"
97 # include <sys/task.h>
101 #include "interfaces.h"
105 __unused __unused static const char rcsid[] = "$Sudo: sudo.c,v 1.369.2.33 2007/12/02 17:13:52 millert Exp $";
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 *));
136 char **Argv, **NewArgv;
138 struct sudo_user sudo_user;
139 struct passwd *auth_pw;
141 struct interface *interfaces;
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
151 #endif /* HAVE_LOGIN_CAP_H */
152 #ifdef HAVE_BSD_AUTH_H
154 #endif /* HAVE_BSD_AUTH_H */
155 sigaction_t saved_sa_int, saved_sa_quit, saved_sa_tstp, saved_sa_chld;
159 main(argc, argv, envp)
170 extern int printmatches;
171 extern char **environ;
173 #ifdef HAVE_SETLOCALE
174 setlocale(LC_ALL, "");
178 if ((Argc = argc) < 1)
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
187 #endif /* HAVE_GETPRPWNAM && HAVE_SET_AUTH_PARAMETERS */
190 errx(1, "must be setuid root");
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.
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);
208 * Turn off core dumps and close open files.
213 /* Parse our arguments. */
214 sudo_mode = parse_args(Argc, Argv);
216 /* Setup defaults data structures. */
219 /* Load the list of local ip addresses and netmasks. */
223 if (ISSET(sudo_mode, MODE_SHELL))
225 else if (ISSET(sudo_mode, MODE_EDIT))
226 user_cmnd = "sudoedit";
230 (void) printf("Sudo version %s\n", version);
233 (void) printf("Sudoers path: %s\n", _PATH_SUDOERS);
244 user_cmnd = "validate";
248 case MODE_INVALIDATE:
263 /* Must have a command to run... */
264 if (user_cmnd == NULL && NewArgc == 0)
267 cmnd_status = init_vars(sudo_mode, environ);
270 validated = sudo_ldap_check(pwflag);
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)
277 check_sudoers(); /* check mode/owner on _PATH_SUDOERS */
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.
282 sudoers_lookup(pwflag);
287 check_sudoers(); /* check mode/owner on _PATH_SUDOERS */
289 /* Validate the user but don't search for pseudo-commands. */
290 validated = sudoers_lookup(pwflag);
292 if (safe_cmnd == NULL)
293 safe_cmnd = estrdup(user_cmnd);
296 * Look up the timestamp dir owner if one is specified.
298 if (def_timestampowner) {
301 if (*def_timestampowner == '#')
302 pw = getpwuid(atoi(def_timestampowner + 1));
304 pw = getpwnam(def_timestampowner);
306 log_error(0, "timestamp owner (%s): No such user",
308 timestamp_uid = pw->pw_uid;
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));
317 if (ISSET(validated, VALIDATE_ERROR))
318 log_error(0, "parse error in %s near line %d", _PATH_SUDOERS,
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",
329 /* If given the -P option, set the "preserve_groups" flag. */
330 if (ISSET(sudo_mode, MODE_PRESERVE_GROUPS))
331 def_preserve_groups = TRUE;
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)
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");
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;
349 /* Build a new environment that avoids any nasty bits. */
350 environ = rebuild_env(environ, sudo_mode, ISSET(validated, FLAG_NOEXEC));
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(validated);
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 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);
374 } else if (cmnd_status == NOT_FOUND) {
375 warnx("%s: command not found", user_cmnd);
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))
383 "sorry, you are not allowed to preserve the environment");
385 validate_env_vars(sudo_user.env_vars);
388 log_auth(validated, 1);
389 if (sudo_mode == MODE_VALIDATE)
391 else if (sudo_mode == MODE_LIST) {
394 sudo_ldap_list_matches();
399 /* Override user's umask if configured to do so. */
400 if (def_umask != 0777)
401 (void) umask(def_umask);
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 */
408 /* Become specified user or root if executing a command. */
409 if (ISSET(sudo_mode, MODE_RUN))
410 set_perms(PERM_FULL_RUNAS);
412 /* Close the password and group files */
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, envp));
433 /* Insert user-specified environment variables. */
434 environ = insert_env_vars(environ, sudo_user.env_vars);
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);
443 if (ISSET(sudo_mode, MODE_BACKGROUND) && fork() > 0)
446 execve(safe_cmnd, NewArgv, environ);
449 #endif /* PROFILING */
451 * If we got here then the exec() failed...
453 if (errno == ENOEXEC) {
454 NewArgv--; /* at least one extra slot... */
456 NewArgv[1] = safe_cmnd;
457 execve(_PATH_BSHELL, NewArgv, environ);
459 warn("unable to execute %s", safe_cmnd);
461 } else if (ISSET(validated, FLAG_NO_USER) || (validated & FLAG_NO_HOST)) {
462 log_auth(validated, 1);
464 } else if (ISSET(validated, VALIDATE_NOT_OK)) {
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.
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);
480 /* Just tell the user they are not allowed to run foo. */
481 log_auth(validated, 1);
485 /* should never get here */
486 log_auth(validated, 1);
489 exit(0); /* not reached */
493 * Initialize timezone, set umask, fill in ``sudo_user'' struct and
494 * load the ``interfaces'' array.
497 init_vars(sudo_mode, envp)
501 char *p, **ep, thost[MAXHOSTNAMELEN];
502 int nohostname, rval;
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]);
509 (void) tzset(); /* set the timezone if applicable */
510 #endif /* HAVE_TZSET */
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));
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.
523 nohostname = gethostname(thost, sizeof(thost));
525 user_host = user_shost = "localhost";
527 user_host = estrdup(thost);
529 /* Defer call to set_fqdn() until log_error() is safe. */
530 user_shost = user_host;
532 if ((p = strchr(user_host, '.'))) {
534 user_shost = estrdup(user_host);
537 user_shost = user_host;
542 if ((p = ttyname(STDIN_FILENO)) || (p = ttyname(STDOUT_FILENO))) {
543 user_tty = user_ttypath = estrdup(p);
544 if (strncmp(user_tty, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
545 user_tty += sizeof(_PATH_DEV) - 1;
547 user_tty = "unknown";
549 for (ep = envp; *ep; ep++) {
552 if (strncmp("PATH=", *ep, 5) == 0)
556 if (strncmp("SHELL=", *ep, 6) == 0)
557 user_shell = *ep + 6;
558 else if (!user_prompt && strncmp("SUDO_PROMPT=", *ep, 12) == 0)
559 user_prompt = *ep + 12;
560 else if (strncmp("SUDO_USER=", *ep, 10) == 0)
561 prev_user = *ep + 10;
568 * Get a local copy of the user's struct passwd with the shadow password
569 * if necessary. It is assumed that euid is 0 at this point so we
570 * can read the shadow passwd file if necessary.
572 if ((sudo_user.pw = sudo_getpwuid(getuid())) == NULL) {
573 /* Need to make a fake struct passwd for logging to work. */
575 char pw_name[MAX_UID_T_LEN + 1];
577 pw.pw_uid = getuid();
578 (void) snprintf(pw_name, sizeof(pw_name), "%lu",
579 (unsigned long) pw.pw_uid);
580 pw.pw_name = pw_name;
584 * If we are in -k/-K mode, just spew to stderr. It is not unusual for
585 * users to place "sudo -k" in a .logout file which can cause sudo to
586 * be run during reboot after the YP/NIS/NIS+/LDAP/etc daemon has died.
588 if (sudo_mode & (MODE_INVALIDATE|MODE_KILL))
589 errx(1, "uid %s does not exist in the passwd file!", pw_name);
590 log_error(0, "uid %s does not exist in the passwd file!", pw_name);
592 if (user_shell == NULL || *user_shell == '\0')
593 user_shell = sudo_user.pw->pw_shell;
595 /* It is now safe to use log_error() and set_perms() */
597 #ifdef HAVE_GETGROUPS
598 if ((user_ngroups = getgroups(0, NULL)) > 0) {
599 user_groups = emalloc2(user_ngroups, sizeof(GETGROUPS_T));
600 if (getgroups(user_ngroups, user_groups) < 0)
601 log_error(USE_ERRNO|MSG_ONLY, "can't get group vector");
607 set_fqdn(); /* may call log_error() */
610 log_error(USE_ERRNO|MSG_ONLY, "can't get hostname");
612 set_runaspw(*user_runas); /* may call log_error() */
613 if (*user_runas[0] == '#' && runas_pw->pw_name && runas_pw->pw_name[0])
614 *user_runas = estrdup(runas_pw->pw_name);
617 * Get current working directory. Try as user, fall back to root.
619 set_perms(PERM_USER);
620 if (!getcwd(user_cwd, sizeof(user_cwd))) {
621 set_perms(PERM_ROOT);
622 if (!getcwd(user_cwd, sizeof(user_cwd))) {
623 warnx("cannot get working directory");
624 (void) strlcpy(user_cwd, "unknown", sizeof(user_cwd));
627 set_perms(PERM_ROOT);
630 * If we were given the '-e', '-i' or '-s' options we need to redo
631 * NewArgv and NewArgc.
633 if ((sudo_mode & (MODE_SHELL | MODE_EDIT))) {
634 char **dst, **src = NewArgv;
636 /* Allocate an extra slot for execve() failure (ENOEXEC). */
637 NewArgv = (char **) emalloc2((++NewArgc + 2), sizeof(char *));
639 if (ISSET(sudo_mode, MODE_EDIT))
640 NewArgv[0] = "sudoedit";
641 else if (ISSET(sudo_mode, MODE_LOGIN_SHELL))
642 NewArgv[0] = runas_pw->pw_shell;
643 else if (user_shell && *user_shell)
644 NewArgv[0] = user_shell;
646 errx(1, "unable to determine shell");
648 /* copy the args from NewArgv */
649 for (dst = NewArgv + 1; (*dst = *src) != NULL; ++src, ++dst)
653 /* Set login class if applicable. */
654 set_loginclass(sudo_user.pw);
656 /* Set project if applicable. */
657 set_project(runas_pw);
659 /* Resolve the path and return. */
661 user_stat = emalloc(sizeof(struct stat));
662 if (sudo_mode & (MODE_RUN | MODE_EDIT)) {
663 if (ISSET(sudo_mode, MODE_RUN)) {
664 /* XXX - default_runas may be modified during parsing of sudoers */
665 set_perms(PERM_RUNAS);
666 rval = find_path(NewArgv[0], &user_cmnd, user_stat, user_path);
667 set_perms(PERM_ROOT);
669 /* Failed as root, try as invoking user. */
670 set_perms(PERM_USER);
671 rval = find_path(NewArgv[0], &user_cmnd, user_stat, user_path);
672 set_perms(PERM_ROOT);
681 /* If we didn't realloc NewArgv it is contiguous so just count. */
682 if (!(sudo_mode & (MODE_SHELL | MODE_EDIT))) {
683 size = (size_t) (NewArgv[NewArgc-1] - NewArgv[1]) +
684 strlen(NewArgv[NewArgc-1]) + 1;
686 for (size = 0, from = NewArgv + 1; *from; from++)
687 size += strlen(*from) + 1;
690 /* Alloc and build up user_args. */
691 user_args = (char *) emalloc(size);
692 for (to = user_args, from = NewArgv + 1; *from; from++) {
693 n = strlcpy(to, *from, size - (to - user_args));
694 if (n >= size - (to - user_args))
695 errx(1, "internal error, init_vars() overflow");
702 if ((user_base = strrchr(user_cmnd, '/')) != NULL)
705 user_base = user_cmnd;
711 * Command line argument parsing, can't use getopt(3).
714 parse_args(argc, argv)
718 int rval = MODE_RUN; /* what mode is sudo to be run in? */
719 int excl = 0; /* exclusive arg, no others allowed */
724 /* First, check to see if we were invoked as "sudoedit". */
725 if (strcmp(getprogname(), "sudoedit") == 0) {
731 while (NewArgc > 0) {
732 if (NewArgv[0][0] == '-') {
733 if (NewArgv[0][1] != '\0' && NewArgv[0][2] != '\0')
734 warnx("please use single character options");
736 switch (NewArgv[0][1]) {
738 /* Must have an associated prompt. */
739 if (NewArgv[1] == NULL)
742 user_prompt = NewArgv[1];
743 def_passprompt_override = TRUE;
749 /* Must have an associated runas user. */
750 if (NewArgv[1] == NULL)
753 user_runas = &NewArgv[1];
758 #ifdef HAVE_BSD_AUTH_H
760 /* Must have an associated authentication style. */
761 if (NewArgv[1] == NULL)
764 login_style = NewArgv[1];
770 #ifdef HAVE_LOGIN_CAP_H
772 /* Must have an associated login class. */
773 if (NewArgv[1] == NULL)
776 login_class = NewArgv[1];
777 def_use_loginclass = TRUE;
784 SET(rval, MODE_BACKGROUND);
788 if (excl && excl != 'e')
793 rval = MODE_VALIDATE;
794 if (excl && excl != 'v')
799 SET(rval, (MODE_LOGIN_SHELL | MODE_SHELL));
800 def_env_reset = TRUE;
801 if (excl && excl != 'i')
806 rval = MODE_INVALIDATE;
807 if (excl && excl != 'k')
813 if (excl && excl != 'K')
818 rval = MODE_LISTDEFS;
819 if (excl && excl != 'L')
825 if (excl && excl != 'l')
831 if (excl && excl != 'V')
837 if (excl && excl != 'h')
842 SET(rval, MODE_SHELL);
843 if (excl && excl != 's')
848 SET(rval, MODE_RESET_HOME);
851 SET(rval, MODE_PRESERVE_GROUPS);
854 SET(tgetpass_flags, TGP_STDIN);
857 SET(rval, MODE_PRESERVE_ENV);
864 warnx("'-' requires an argument");
867 warnx("illegal option `%s'", NewArgv[0]);
870 } else if (NewArgv[0][0] != '/' && strchr(NewArgv[0], '=') != NULL) {
871 /* Could be an environment variable. */
872 struct list_member *ev;
873 ev = emalloc(sizeof(*ev));
874 ev->value = NewArgv[0];
875 ev->next = sudo_user.env_vars;
876 sudo_user.env_vars = ev;
886 if (ISSET(rval, MODE_EDIT) &&
887 (ISSET(rval, MODE_PRESERVE_ENV) || sudo_user.env_vars != NULL)) {
888 if (ISSET(rval, MODE_PRESERVE_ENV))
889 warnx("the `-E' option is not valid in edit mode");
890 if (sudo_user.env_vars != NULL)
891 warnx("you may not specify environment variables in edit mode");
895 if (user_runas != NULL && !ISSET(rval, (MODE_EDIT|MODE_RUN))) {
897 warnx("the `-u' and '-%c' options may not be used together", excl);
900 if ((NewArgc == 0 && (rval & MODE_EDIT)) ||
901 (NewArgc > 0 && !(rval & (MODE_RUN | MODE_EDIT))))
903 if (NewArgc == 0 && rval == MODE_RUN)
904 SET(rval, (MODE_IMPLIED_SHELL | MODE_SHELL));
910 * Sanity check sudoers mode/owner/type.
911 * Leaves a file pointer to the sudoers file open in ``fp''.
920 * Fix the mode and group on sudoers file from old default.
921 * Only works if file system is readable/writable by root.
923 if ((rootstat = stat_sudoers(_PATH_SUDOERS, &statbuf)) == 0 &&
924 SUDOERS_UID == statbuf.st_uid && SUDOERS_MODE != 0400 &&
925 (statbuf.st_mode & 0007777) == 0400) {
927 if (chmod(_PATH_SUDOERS, SUDOERS_MODE) == 0) {
928 warnx("fixed mode on %s", _PATH_SUDOERS);
929 SET(statbuf.st_mode, SUDOERS_MODE);
930 if (statbuf.st_gid != SUDOERS_GID) {
931 if (!chown(_PATH_SUDOERS,(uid_t) -1,SUDOERS_GID)) {
932 warnx("set group on %s", _PATH_SUDOERS);
933 statbuf.st_gid = SUDOERS_GID;
935 warn("unable to set group on %s", _PATH_SUDOERS);
938 warn("unable to fix mode on %s", _PATH_SUDOERS);
942 * Sanity checks on sudoers file. Must be done as sudoers
943 * file owner. We already did a stat as root, so use that
944 * data if we can't stat as sudoers file owner.
946 set_perms(PERM_SUDOERS);
948 if (rootstat != 0 && stat_sudoers(_PATH_SUDOERS, &statbuf) != 0)
949 log_error(USE_ERRNO, "can't stat %s", _PATH_SUDOERS);
950 else if (!S_ISREG(statbuf.st_mode))
951 log_error(0, "%s is not a regular file", _PATH_SUDOERS);
952 else if (statbuf.st_size == 0)
953 log_error(0, "%s is zero length", _PATH_SUDOERS);
954 else if ((statbuf.st_mode & 07777) != SUDOERS_MODE)
955 log_error(0, "%s is mode 0%o, should be 0%o", _PATH_SUDOERS,
956 (unsigned int) (statbuf.st_mode & 07777),
957 (unsigned int) SUDOERS_MODE);
958 else if (statbuf.st_uid != SUDOERS_UID)
959 log_error(0, "%s is owned by uid %lu, should be %lu", _PATH_SUDOERS,
960 (unsigned long) statbuf.st_uid, (unsigned long) SUDOERS_UID);
961 else if (statbuf.st_gid != SUDOERS_GID)
962 log_error(0, "%s is owned by gid %lu, should be %lu", _PATH_SUDOERS,
963 (unsigned long) statbuf.st_gid, (unsigned long) SUDOERS_GID);
965 /* Solaris sometimes returns EAGAIN so try 10 times */
966 for (i = 0; i < 10 ; i++) {
968 if ((sudoers_fp = fopen(_PATH_SUDOERS, "r")) == NULL ||
969 fgetc(sudoers_fp) == EOF) {
970 if (sudoers_fp != NULL)
973 if (errno != EAGAIN && errno != EWOULDBLOCK)
979 if (sudoers_fp == NULL)
980 log_error(USE_ERRNO, "can't open %s", _PATH_SUDOERS);
983 set_perms(PERM_ROOT); /* change back to root */
987 * Close all open files (except std*) and turn off core dumps.
992 int miss[3], devnull = -1;
993 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
997 * Turn off core dumps.
999 (void) getrlimit(RLIMIT_CORE, &corelimit);
1000 memcpy(&rl, &corelimit, sizeof(struct rlimit));
1002 (void) setrlimit(RLIMIT_CORE, &rl);
1003 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
1006 * stdin, stdout and stderr must be open; set them to /dev/null
1007 * if they are closed and close all other fds.
1009 miss[STDIN_FILENO] = fcntl(STDIN_FILENO, F_GETFL, 0) == -1;
1010 miss[STDOUT_FILENO] = fcntl(STDOUT_FILENO, F_GETFL, 0) == -1;
1011 miss[STDERR_FILENO] = fcntl(STDERR_FILENO, F_GETFL, 0) == -1;
1012 if (miss[STDIN_FILENO] || miss[STDOUT_FILENO] || miss[STDERR_FILENO]) {
1013 if ((devnull = open(_PATH_DEVNULL, O_RDWR, 0644)) != -1) {
1014 if (miss[STDIN_FILENO])
1015 (void) dup2(devnull, STDIN_FILENO);
1016 if (miss[STDOUT_FILENO])
1017 (void) dup2(devnull, STDOUT_FILENO);
1018 if (miss[STDERR_FILENO])
1019 (void) dup2(devnull, STDERR_FILENO);
1022 closefrom(STDERR_FILENO + 1);
1025 #ifdef HAVE_LOGIN_CAP_H
1033 * Don't make it a fatal error if the user didn't specify the login
1034 * class themselves. We do this because if login.conf gets
1035 * corrupted we want the admin to be able to use sudo to fix it.
1038 errflags = NO_MAIL|MSG_ONLY;
1040 errflags = NO_MAIL|MSG_ONLY|NO_EXIT;
1042 if (login_class && strcmp(login_class, "-") != 0) {
1043 if (strcmp(*user_runas, "root") != 0 && user_uid != 0)
1044 errx(1, "only root can use -c %s", login_class);
1046 login_class = pw->pw_class;
1047 if (!login_class || !*login_class)
1049 (pw->pw_uid == 0) ? LOGIN_DEFROOTCLASS : LOGIN_DEFCLASS;
1052 lc = login_getclass(login_class);
1053 if (!lc || !lc->lc_class || strcmp(lc->lc_class, login_class) != 0) {
1054 log_error(errflags, "unknown login class: %s", login_class);
1056 lc = login_getclass(NULL); /* needed for login_getstyle() later */
1065 #endif /* HAVE_LOGIN_CAP_H */
1067 #ifdef HAVE_PROJECT_H
1072 int errflags = NO_MAIL|MSG_ONLY|NO_EXIT;
1074 struct project proj;
1075 struct project *resultp = '\0';
1079 * Collect the default project for the user and settaskid
1082 if (resultp = getdefaultproj(pw->pw_name, &proj, buf, sizeof(buf))) {
1083 errval = setproject(resultp->pj_name, pw->pw_name, TASK_NORMAL);
1086 case SETPROJ_ERR_TASK:
1087 if (errno == EAGAIN)
1088 log_error(errflags, "resource control limit has been reached");
1089 else if (errno == ESRCH)
1090 log_error(errflags, "user \"%s\" is not a member of "
1091 "project \"%s\"", pw->pw_name, resultp->pj_name);
1092 else if (errno == EACCES)
1093 log_error(errflags, "the invoking task is final");
1095 log_error(errflags, "could not join project \"%s\"",
1098 case SETPROJ_ERR_POOL:
1099 if (errno == EACCES)
1100 log_error(errflags, "no resource pool accepting "
1101 "default bindings exists for project \"%s\"",
1103 else if (errno == ESRCH)
1104 log_error(errflags, "specified resource pool does "
1105 "not exist for project \"%s\"", resultp->pj_name);
1107 log_error(errflags, "could not bind to default "
1108 "resource pool for project \"%s\"", resultp->pj_name);
1112 log_error(errflags, "setproject failed for project \"%s\"",
1115 log_error(errflags, "warning, resource control assignment "
1116 "failed for project \"%s\"", resultp->pj_name);
1121 log_error(errflags, "getdefaultproj() error: %s", strerror(errno));
1131 #endif /* HAVE_PROJECT_H */
1134 * Look up the fully qualified domain name and set user_host and user_shost.
1139 #ifdef HAVE_GETADDRINFO
1140 struct addrinfo *res0, hint;
1146 #ifdef HAVE_GETADDRINFO
1147 memset(&hint, 0, sizeof(hint));
1148 hint.ai_family = PF_UNSPEC;
1149 hint.ai_flags = AI_CANONNAME;
1150 if (getaddrinfo(user_host, NULL, &hint, &res0) != 0) {
1152 if (!(hp = gethostbyname(user_host))) {
1154 log_error(MSG_ONLY|NO_EXIT,
1155 "unable to resolve host %s", user_host);
1157 if (user_shost != user_host)
1160 #ifdef HAVE_GETADDRINFO
1161 user_host = estrdup(res0->ai_canonname);
1164 user_host = estrdup(hp->h_name);
1167 if ((p = strchr(user_host, '.'))) {
1169 user_shost = estrdup(user_host);
1172 user_shost = user_host;
1177 * Get passwd entry for the user we are going to run commands as.
1178 * By default, this is "root". Updates runas_pw as a side effect.
1184 if (runas_pw != NULL) {
1185 if (user_runas != &def_runas_default)
1186 return(TRUE); /* don't override -u option */
1190 runas_pw = sudo_getpwuid(atoi(user + 1));
1191 if (runas_pw == NULL) {
1192 runas_pw = emalloc(sizeof(struct passwd));
1193 (void) memset((VOID *)runas_pw, 0, sizeof(struct passwd));
1194 runas_pw->pw_uid = atoi(user + 1);
1197 runas_pw = sudo_getpwnam(user);
1198 if (runas_pw == NULL)
1199 log_error(NO_MAIL|MSG_ONLY, "no passwd entry for %s!", user);
1205 * Get passwd entry for the user we are going to authenticate as.
1206 * By default, this is the user invoking sudo. In the most common
1207 * case, this matches sudo_user.pw or runas_pw.
1209 static struct passwd *
1215 if (runas_pw->pw_uid == 0)
1217 else if ((pw = sudo_getpwuid(0)) == NULL)
1218 log_error(0, "uid 0 does not exist in the passwd file!");
1219 } else if (def_runaspw) {
1220 if (strcmp(def_runas_default, *user_runas) == 0)
1222 else if ((pw = sudo_getpwnam(def_runas_default)) == NULL)
1223 log_error(0, "user %s does not exist in the passwd file!",
1225 } else if (def_targetpw) {
1226 if (runas_pw->pw_name == NULL)
1227 log_error(NO_MAIL|MSG_ONLY, "no passwd entry for %lu!",
1228 (unsigned long) runas_pw->pw_uid);
1237 * Tell which options are mutually exclusive and exit.
1240 usage_excl(exit_val)
1243 warnx("Only one of the -e, -h, i, -k, -K, -l, -s, -v or -V options may be used");
1248 * Give usage message and exit.
1254 char **p, **uvec[4];
1255 int i, linelen, linemax, ulen, plen;
1256 static char *uvec1[] = {
1266 static char *uvec2[] = {
1268 #ifdef HAVE_BSD_AUTH_H
1271 #ifdef HAVE_LOGIN_CAP_H
1275 " [-u username|#uid]",
1277 " {-i | -s | <command>}",
1280 static char *uvec3[] = {
1283 #ifdef HAVE_BSD_AUTH_H
1286 #ifdef HAVE_LOGIN_CAP_H
1290 " [-u username|#uid]",
1296 * Use usage vectors appropriate to the progname.
1298 if (strcmp(getprogname(), "sudoedit") == 0) {
1299 uvec[0] = uvec3 + 1;
1309 * Print usage and wrap lines as needed.
1310 * Assumes an 80-character wide terminal, which is kind of bogus...
1312 ulen = (int)strlen(getprogname()) + 7;
1314 for (i = 0; uvec[i] != NULL; i++) {
1315 printf("usage: %s", getprogname());
1316 linelen = linemax - ulen;
1317 for (p = uvec[i]; *p != NULL; p++) {
1318 plen = (int)strlen(*p);
1319 if (linelen >= plen || linelen == linemax - ulen) {
1324 linelen = linemax - ulen;
1325 printf("\n%*s", ulen, "");