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>
100 # include <selinux/selinux.h>
104 #include "interfaces.h"
108 __unused __unused static const char rcsid[] = "$Sudo: sudo.c,v 1.369.2.41 2008/06/21 19:04:07 millert Exp $";
114 static int init_vars __P((int, char **));
115 static int parse_args __P((int, char **));
116 static void check_sudoers __P((void));
117 static void initial_setup __P((void));
118 static void set_loginclass __P((struct passwd *));
119 static void set_project __P((struct passwd *));
120 static void usage __P((int))
121 __attribute__((__noreturn__));
122 static void usage_excl __P((int))
123 __attribute__((__noreturn__));
124 static void usage_excl __P((int));
125 static struct passwd *get_authpw __P((void));
126 extern int sudo_edit __P((int, char **, char **));
127 extern void list_matches __P((void));
128 extern char **rebuild_env __P((char **, int, int));
129 extern void validate_env_vars __P((struct list_member *));
130 extern char **insert_env_vars __P((char **, struct list_member *));
131 extern struct passwd *sudo_getpwnam __P((const char *));
132 extern struct passwd *sudo_getpwuid __P((uid_t));
133 extern struct passwd *sudo_pwdup __P((const struct passwd *));
139 char **Argv, **NewArgv;
141 struct sudo_user sudo_user;
142 struct passwd *auth_pw;
144 struct interface *interfaces;
148 extern int errorlineno;
149 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
150 static struct rlimit corelimit;
151 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
152 #ifdef HAVE_LOGIN_CAP_H
154 #endif /* HAVE_LOGIN_CAP_H */
155 #ifdef HAVE_BSD_AUTH_H
157 #endif /* HAVE_BSD_AUTH_H */
158 sigaction_t saved_sa_int, saved_sa_quit, saved_sa_tstp;
162 main(argc, argv, envp)
173 extern int printmatches;
174 extern char **environ;
176 #ifdef HAVE_SETLOCALE
177 setlocale(LC_ALL, "");
181 if ((Argc = argc) < 1)
184 /* Must be done as the first thing... */
185 #if defined(HAVE_GETPRPWNAM) && defined(HAVE_SET_AUTH_PARAMETERS)
186 (void) set_auth_parameters(Argc, Argv);
187 # ifdef HAVE_INITPRIVS
190 #endif /* HAVE_GETPRPWNAM && HAVE_SET_AUTH_PARAMETERS */
193 errx(1, "must be setuid root");
197 * Ignore keyboard-generated signals so the user cannot interrupt
198 * us at some point and avoid the logging.
199 * Install handler to wait for children when they exit.
201 sigemptyset(&sa.sa_mask);
202 sa.sa_flags = SA_RESTART;
203 sa.sa_handler = SIG_IGN;
204 (void) sigaction(SIGINT, &sa, &saved_sa_int);
205 (void) sigaction(SIGQUIT, &sa, &saved_sa_quit);
206 (void) sigaction(SIGTSTP, &sa, &saved_sa_tstp);
209 * Turn off core dumps and close open files.
214 /* Parse our arguments. */
215 sudo_mode = parse_args(Argc, Argv);
217 /* Setup defaults data structures. */
220 /* Load the list of local ip addresses and netmasks. */
224 if (ISSET(sudo_mode, MODE_SHELL))
226 else if (ISSET(sudo_mode, MODE_EDIT))
227 user_cmnd = "sudoedit";
231 (void) printf("Sudo version %s\n", version);
234 (void) printf("Sudoers path: %s\n", _PATH_SUDOERS);
245 user_cmnd = "validate";
249 case MODE_INVALIDATE:
264 /* Must have a command to run... */
265 if (user_cmnd == NULL && NewArgc == 0)
268 cmnd_status = init_vars(sudo_mode, environ);
271 validated = sudo_ldap_check(pwflag);
273 /* Skip reading /etc/sudoers if LDAP told us to */
274 if (!def_ignore_local_sudoers) {
277 check_sudoers(); /* check mode/owner on _PATH_SUDOERS */
279 /* Local sudoers file overrides LDAP if we have a match. */
280 v = sudoers_lookup(pwflag);
281 if (validated == VALIDATE_ERROR || ISSET(v, VALIDATE_OK))
285 check_sudoers(); /* check mode/owner on _PATH_SUDOERS */
287 /* Validate the user but don't search for pseudo-commands. */
288 validated = sudoers_lookup(pwflag);
290 if (safe_cmnd == NULL)
291 safe_cmnd = estrdup(user_cmnd);
294 * Look up the timestamp dir owner if one is specified.
296 if (def_timestampowner) {
299 if (*def_timestampowner == '#')
300 pw = getpwuid(atoi(def_timestampowner + 1));
302 pw = getpwnam(def_timestampowner);
304 log_error(0, "timestamp owner (%s): No such user",
306 timestamp_uid = pw->pw_uid;
309 /* This goes after the sudoers parse since we honor sudoers options. */
310 if (sudo_mode == MODE_KILL || sudo_mode == MODE_INVALIDATE) {
311 remove_timestamp((sudo_mode == MODE_KILL));
315 if (ISSET(validated, VALIDATE_ERROR))
316 log_error(0, "parse error in %s near line %d", _PATH_SUDOERS,
319 /* Is root even allowed to run sudo? */
320 if (user_uid == 0 && !def_root_sudo) {
321 (void) fprintf(stderr,
322 "Sorry, %s has been configured to not allow root to run it.\n",
327 /* If given the -P option, set the "preserve_groups" flag. */
328 if (ISSET(sudo_mode, MODE_PRESERVE_GROUPS))
329 def_preserve_groups = TRUE;
331 /* If no command line args and "set_home" is not set, error out. */
332 if (ISSET(sudo_mode, MODE_IMPLIED_SHELL) && !def_shell_noargs)
335 /* Bail if a tty is required and we don't have one. */
336 if (def_requiretty) {
337 if ((fd = open(_PATH_TTY, O_RDWR|O_NOCTTY)) == -1)
338 log_error(NO_MAIL, "sorry, you must have a tty to run sudo");
343 /* User may have overriden environment resetting via the -E flag. */
344 if (ISSET(sudo_mode, MODE_PRESERVE_ENV) && ISSET(validated, FLAG_SETENV))
345 def_env_reset = FALSE;
347 /* Build a new environment that avoids any nasty bits. */
348 environ = rebuild_env(environ, sudo_mode, ISSET(validated, FLAG_NOEXEC));
350 /* Fill in passwd struct based on user we are authenticating as. */
351 auth_pw = get_authpw();
353 /* Require a password if sudoers says so. */
354 if (!ISSET(validated, FLAG_NOPASS))
355 check_user(validated);
357 /* If run as root with SUDO_USER set, set sudo_user.pw to that user. */
358 if (user_uid == 0 && prev_user != NULL && strcmp(prev_user, "root") != 0) {
361 if ((pw = sudo_getpwnam(prev_user)) != NULL) {
367 if (ISSET(validated, VALIDATE_OK)) {
368 /* Finally tell the user if the command did not exist. */
369 if (cmnd_status == NOT_FOUND_DOT) {
370 warnx("ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run.", user_cmnd, user_cmnd, user_cmnd);
372 } else if (cmnd_status == NOT_FOUND) {
373 warnx("%s: command not found", user_cmnd);
377 /* If user specified env vars make sure sudoers allows it. */
378 if (ISSET(sudo_mode, MODE_RUN) && !ISSET(validated, FLAG_SETENV)) {
379 if (ISSET(sudo_mode, MODE_PRESERVE_ENV))
381 "sorry, you are not allowed to preserve the environment");
383 validate_env_vars(sudo_user.env_vars);
386 log_auth(validated, 1);
387 if (sudo_mode == MODE_VALIDATE)
389 else if (sudo_mode == MODE_LIST) {
392 sudo_ldap_list_matches();
397 /* Override user's umask if configured to do so. */
398 if (def_umask != 0777)
399 (void) umask(def_umask);
401 /* Restore coredumpsize resource limit. */
402 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
403 (void) setrlimit(RLIMIT_CORE, &corelimit);
404 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
406 /* Become specified user or root if executing a command. */
407 if (ISSET(sudo_mode, MODE_RUN))
408 set_perms(PERM_FULL_RUNAS);
410 /* Close the password and group files */
414 if (ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
417 /* Convert /bin/sh -> -sh so shell knows it is a login shell */
418 if ((p = strrchr(NewArgv[0], '/')) == NULL)
423 /* Change to target user's homedir. */
424 if (chdir(runas_pw->pw_dir) == -1)
425 warn("unable to change directory to %s", runas_pw->pw_dir);
428 if (ISSET(sudo_mode, MODE_EDIT))
429 exit(sudo_edit(NewArgc, NewArgv, envp));
431 /* Insert user-specified environment variables. */
432 environ = insert_env_vars(environ, sudo_user.env_vars);
434 /* Restore signal handlers before we exec. */
435 (void) sigaction(SIGINT, &saved_sa_int, NULL);
436 (void) sigaction(SIGQUIT, &saved_sa_quit, NULL);
437 (void) sigaction(SIGTSTP, &saved_sa_tstp, NULL);
440 if (ISSET(sudo_mode, MODE_BACKGROUND) && fork() > 0)
444 if (is_selinux_enabled() > 0 && user_role != NULL)
445 selinux_exec(user_role, user_type, NewArgv, environ,
446 ISSET(sudo_mode, MODE_LOGIN_SHELL));
448 execve(safe_cmnd, NewArgv, environ);
452 #endif /* PROFILING */
454 * If we got here then the exec() failed...
456 if (errno == ENOEXEC) {
457 NewArgv--; /* at least one extra slot... */
459 NewArgv[1] = safe_cmnd;
460 execve(_PATH_BSHELL, NewArgv, environ);
462 warn("unable to execute %s", safe_cmnd);
464 } else if (ISSET(validated, FLAG_NO_USER) || (validated & FLAG_NO_HOST)) {
465 log_auth(validated, 1);
467 } else if (ISSET(validated, VALIDATE_NOT_OK)) {
470 * We'd like to not leak path info at all here, but that can
471 * *really* confuse the users. To really close the leak we'd
472 * have to say "not allowed to run foo" even when the problem
473 * is just "no foo in path" since the user can trivially set
474 * their path to just contain a single dir.
477 !(cmnd_status == NOT_FOUND_DOT || cmnd_status == NOT_FOUND));
478 if (cmnd_status == NOT_FOUND)
479 warnx("%s: command not found", user_cmnd);
480 else if (cmnd_status == NOT_FOUND_DOT)
481 warnx("ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run.", user_cmnd, user_cmnd, user_cmnd);
483 /* Just tell the user they are not allowed to run foo. */
484 log_auth(validated, 1);
488 /* should never get here */
489 log_auth(validated, 1);
492 exit(0); /* not reached */
496 * Initialize timezone, set umask, fill in ``sudo_user'' struct and
497 * load the ``interfaces'' array.
500 init_vars(sudo_mode, envp)
504 char *p, **ep, thost[MAXHOSTNAMELEN];
505 int nohostname, rval;
507 /* Sanity check command from user. */
508 if (user_cmnd == NULL && strlen(NewArgv[0]) >= PATH_MAX)
509 errx(1, "%s: File name too long", NewArgv[0]);
512 (void) tzset(); /* set the timezone if applicable */
513 #endif /* HAVE_TZSET */
515 /* Default value for cmnd and cwd, overridden later. */
516 if (user_cmnd == NULL)
517 user_cmnd = NewArgv[0];
518 (void) strlcpy(user_cwd, "unknown", sizeof(user_cwd));
521 * We avoid gethostbyname() if possible since we don't want
522 * sudo to block if DNS or NIS is hosed.
523 * "host" is the (possibly fully-qualified) hostname and
524 * "shost" is the unqualified form of the hostname.
526 nohostname = gethostname(thost, sizeof(thost));
528 user_host = user_shost = "localhost";
530 user_host = estrdup(thost);
532 /* Defer call to set_fqdn() until log_error() is safe. */
533 user_shost = user_host;
535 if ((p = strchr(user_host, '.'))) {
537 user_shost = estrdup(user_host);
540 user_shost = user_host;
545 if ((p = ttyname(STDIN_FILENO)) || (p = ttyname(STDOUT_FILENO))) {
546 user_tty = user_ttypath = estrdup(p);
547 if (strncmp(user_tty, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
548 user_tty += sizeof(_PATH_DEV) - 1;
550 user_tty = "unknown";
552 for (ep = envp; *ep; ep++) {
555 if (strncmp("PATH=", *ep, 5) == 0)
559 if (strncmp("SHELL=", *ep, 6) == 0)
560 user_shell = *ep + 6;
561 else if (!user_prompt && strncmp("SUDO_PROMPT=", *ep, 12) == 0)
562 user_prompt = *ep + 12;
563 else if (strncmp("SUDO_USER=", *ep, 10) == 0)
564 prev_user = *ep + 10;
571 * Get a local copy of the user's struct passwd with the shadow password
572 * if necessary. It is assumed that euid is 0 at this point so we
573 * can read the shadow passwd file if necessary.
575 if ((sudo_user.pw = sudo_getpwuid(getuid())) == NULL) {
576 /* Need to make a fake struct passwd for logging to work. */
578 char pw_name[MAX_UID_T_LEN + 1];
580 pw.pw_uid = getuid();
581 (void) snprintf(pw_name, sizeof(pw_name), "%lu",
582 (unsigned long) pw.pw_uid);
583 pw.pw_name = pw_name;
587 * If we are in -k/-K mode, just spew to stderr. It is not unusual for
588 * users to place "sudo -k" in a .logout file which can cause sudo to
589 * be run during reboot after the YP/NIS/NIS+/LDAP/etc daemon has died.
591 if (sudo_mode & (MODE_INVALIDATE|MODE_KILL))
592 errx(1, "uid %s does not exist in the passwd file!", pw_name);
593 log_error(0, "uid %s does not exist in the passwd file!", pw_name);
595 if (user_shell == NULL || *user_shell == '\0')
596 user_shell = sudo_user.pw->pw_shell;
598 /* It is now safe to use log_error() and set_perms() */
600 #ifdef HAVE_GETGROUPS
601 if ((user_ngroups = getgroups(0, NULL)) > 0) {
602 user_groups = emalloc2(user_ngroups, sizeof(GETGROUPS_T));
603 if (getgroups(user_ngroups, user_groups) < 0)
604 log_error(USE_ERRNO|MSG_ONLY, "can't get group vector");
610 set_fqdn(); /* may call log_error() */
613 log_error(USE_ERRNO|MSG_ONLY, "can't get hostname");
615 set_runaspw(*user_runas); /* may call log_error() */
616 if (*user_runas[0] == '#' && runas_pw->pw_name && runas_pw->pw_name[0])
617 *user_runas = estrdup(runas_pw->pw_name);
620 * Get current working directory. Try as user, fall back to root.
622 set_perms(PERM_USER);
623 if (!getcwd(user_cwd, sizeof(user_cwd))) {
624 set_perms(PERM_ROOT);
625 if (!getcwd(user_cwd, sizeof(user_cwd))) {
626 warnx("cannot get working directory");
627 (void) strlcpy(user_cwd, "unknown", sizeof(user_cwd));
630 set_perms(PERM_ROOT);
633 * If we were given the '-e', '-i' or '-s' options we need to redo
634 * NewArgv and NewArgc.
636 if ((sudo_mode & (MODE_SHELL | MODE_EDIT))) {
637 char **dst, **src = NewArgv;
639 /* Allocate an extra slot for execve() failure (ENOEXEC). */
640 NewArgv = (char **) emalloc2((++NewArgc + 2), sizeof(char *));
642 if (ISSET(sudo_mode, MODE_EDIT))
643 NewArgv[0] = "sudoedit";
644 else if (ISSET(sudo_mode, MODE_LOGIN_SHELL))
645 NewArgv[0] = runas_pw->pw_shell;
646 else if (user_shell && *user_shell)
647 NewArgv[0] = user_shell;
649 errx(1, "unable to determine shell");
651 /* copy the args from NewArgv */
652 for (dst = NewArgv + 1; (*dst = *src) != NULL; ++src, ++dst)
656 /* Set login class if applicable. */
657 set_loginclass(sudo_user.pw);
659 /* Set project if applicable. */
660 set_project(runas_pw);
662 /* Resolve the path and return. */
664 user_stat = emalloc(sizeof(struct stat));
665 if (sudo_mode & (MODE_RUN | MODE_EDIT)) {
666 if (ISSET(sudo_mode, MODE_RUN)) {
667 /* XXX - default_runas may be modified during parsing of sudoers */
668 set_perms(PERM_RUNAS);
669 rval = find_path(NewArgv[0], &user_cmnd, user_stat, user_path);
670 set_perms(PERM_ROOT);
672 /* Failed as root, try as invoking user. */
673 set_perms(PERM_USER);
674 rval = find_path(NewArgv[0], &user_cmnd, user_stat, user_path);
675 set_perms(PERM_ROOT);
684 /* If we didn't realloc NewArgv it is contiguous so just count. */
685 if (!(sudo_mode & (MODE_SHELL | MODE_EDIT))) {
686 size = (size_t) (NewArgv[NewArgc-1] - NewArgv[1]) +
687 strlen(NewArgv[NewArgc-1]) + 1;
689 for (size = 0, from = NewArgv + 1; *from; from++)
690 size += strlen(*from) + 1;
693 /* Alloc and build up user_args. */
694 user_args = (char *) emalloc(size);
695 for (to = user_args, from = NewArgv + 1; *from; from++) {
696 n = strlcpy(to, *from, size - (to - user_args));
697 if (n >= size - (to - user_args))
698 errx(1, "internal error, init_vars() overflow");
705 if ((user_base = strrchr(user_cmnd, '/')) != NULL)
708 user_base = user_cmnd;
714 * Command line argument parsing, can't use getopt(3).
717 parse_args(argc, argv)
721 int rval = MODE_RUN; /* what mode is sudo to be run in? */
722 int excl = 0; /* exclusive arg, no others allowed */
727 /* First, check to see if we were invoked as "sudoedit". */
728 if (strcmp(getprogname(), "sudoedit") == 0) {
734 while (NewArgc > 0) {
735 if (NewArgv[0][0] == '-') {
736 if (NewArgv[0][1] != '\0' && NewArgv[0][2] != '\0') {
737 warnx("please use single character options");
741 switch (NewArgv[0][1]) {
743 /* Must have an associated prompt. */
744 if (NewArgv[1] == NULL)
747 user_prompt = NewArgv[1];
748 def_passprompt_override = TRUE;
754 /* Must have an associated runas user. */
755 if (NewArgv[1] == NULL)
758 user_runas = &NewArgv[1];
763 #ifdef HAVE_BSD_AUTH_H
765 /* Must have an associated authentication style. */
766 if (NewArgv[1] == NULL)
769 login_style = NewArgv[1];
775 #ifdef HAVE_LOGIN_CAP_H
777 /* Must have an associated login class. */
778 if (NewArgv[1] == NULL)
781 login_class = NewArgv[1];
782 def_use_loginclass = TRUE;
789 SET(rval, MODE_BACKGROUND);
793 if (excl && excl != 'e')
798 rval = MODE_VALIDATE;
799 if (excl && excl != 'v')
804 SET(rval, (MODE_LOGIN_SHELL | MODE_SHELL));
805 def_env_reset = TRUE;
806 if (excl && excl != 'i')
811 rval = MODE_INVALIDATE;
812 if (excl && excl != 'k')
818 if (excl && excl != 'K')
823 rval = MODE_LISTDEFS;
824 if (excl && excl != 'L')
830 if (excl && excl != 'l')
836 if (excl && excl != 'V')
842 if (excl && excl != 'h')
847 SET(rval, MODE_SHELL);
848 if (excl && excl != 's')
853 SET(rval, MODE_RESET_HOME);
856 SET(rval, MODE_PRESERVE_GROUPS);
859 SET(tgetpass_flags, TGP_STDIN);
862 SET(rval, MODE_PRESERVE_ENV);
866 /* Must have an associated SELinux role. */
867 if (NewArgv[1] == NULL)
870 user_role = NewArgv[1];
876 /* Must have an associated SELinux type. */
877 if (NewArgv[1] == NULL)
880 user_type = NewArgv[1];
891 warnx("'-' requires an argument");
894 warnx("illegal option `%s'", NewArgv[0]);
897 } else if (NewArgv[0][0] != '/' && strchr(NewArgv[0], '=') != NULL) {
898 /* Could be an environment variable. */
899 struct list_member *ev;
900 ev = emalloc(sizeof(*ev));
901 ev->value = NewArgv[0];
902 ev->next = sudo_user.env_vars;
903 sudo_user.env_vars = ev;
913 if (ISSET(rval, MODE_EDIT) &&
914 (ISSET(rval, MODE_PRESERVE_ENV) || sudo_user.env_vars != NULL)) {
915 if (ISSET(rval, MODE_PRESERVE_ENV))
916 warnx("the `-E' option is not valid in edit mode");
917 if (sudo_user.env_vars != NULL)
918 warnx("you may not specify environment variables in edit mode");
921 if (ISSET(rval, MODE_PRESERVE_ENV) && ISSET(rval, MODE_LOGIN_SHELL)) {
922 warnx("you may not specify both the `-i' and `-E' options");
925 if (user_runas != NULL && !ISSET(rval, (MODE_EDIT|MODE_RUN))) {
927 warnx("the `-u' and '-%c' options may not be used together", excl);
930 if ((NewArgc == 0 && (rval & MODE_EDIT)) ||
931 (NewArgc > 0 && !(rval & (MODE_RUN | MODE_EDIT))))
933 if (NewArgc == 0 && rval == MODE_RUN)
934 SET(rval, (MODE_IMPLIED_SHELL | MODE_SHELL));
940 * Sanity check sudoers mode/owner/type.
941 * Leaves a file pointer to the sudoers file open in ``fp''.
950 * Fix the mode and group on sudoers file from old default.
951 * Only works if file system is readable/writable by root.
953 if ((rootstat = stat_sudoers(_PATH_SUDOERS, &statbuf)) == 0 &&
954 SUDOERS_UID == statbuf.st_uid && SUDOERS_MODE != 0400 &&
955 (statbuf.st_mode & 0007777) == 0400) {
957 if (chmod(_PATH_SUDOERS, SUDOERS_MODE) == 0) {
958 warnx("fixed mode on %s", _PATH_SUDOERS);
959 SET(statbuf.st_mode, SUDOERS_MODE);
960 if (statbuf.st_gid != SUDOERS_GID) {
961 if (!chown(_PATH_SUDOERS,(uid_t) -1,SUDOERS_GID)) {
962 warnx("set group on %s", _PATH_SUDOERS);
963 statbuf.st_gid = SUDOERS_GID;
965 warn("unable to set group on %s", _PATH_SUDOERS);
968 warn("unable to fix mode on %s", _PATH_SUDOERS);
972 * Sanity checks on sudoers file. Must be done as sudoers
973 * file owner. We already did a stat as root, so use that
974 * data if we can't stat as sudoers file owner.
976 set_perms(PERM_SUDOERS);
978 if (rootstat != 0 && stat_sudoers(_PATH_SUDOERS, &statbuf) != 0)
979 log_error(USE_ERRNO, "can't stat %s", _PATH_SUDOERS);
980 else if (!S_ISREG(statbuf.st_mode))
981 log_error(0, "%s is not a regular file", _PATH_SUDOERS);
982 else if (statbuf.st_size == 0)
983 log_error(0, "%s is zero length", _PATH_SUDOERS);
984 else if ((statbuf.st_mode & 07777) != SUDOERS_MODE)
985 log_error(0, "%s is mode 0%o, should be 0%o", _PATH_SUDOERS,
986 (unsigned int) (statbuf.st_mode & 07777),
987 (unsigned int) SUDOERS_MODE);
988 else if (statbuf.st_uid != SUDOERS_UID)
989 log_error(0, "%s is owned by uid %lu, should be %lu", _PATH_SUDOERS,
990 (unsigned long) statbuf.st_uid, (unsigned long) SUDOERS_UID);
991 else if (statbuf.st_gid != SUDOERS_GID)
992 log_error(0, "%s is owned by gid %lu, should be %lu", _PATH_SUDOERS,
993 (unsigned long) statbuf.st_gid, (unsigned long) SUDOERS_GID);
995 /* Solaris sometimes returns EAGAIN so try 10 times */
996 for (i = 0; i < 10 ; i++) {
998 if ((sudoers_fp = fopen(_PATH_SUDOERS, "r")) == NULL ||
999 fgetc(sudoers_fp) == EOF) {
1000 if (sudoers_fp != NULL)
1003 if (errno != EAGAIN && errno != EWOULDBLOCK)
1009 if (sudoers_fp == NULL)
1010 log_error(USE_ERRNO, "can't open %s", _PATH_SUDOERS);
1013 set_perms(PERM_ROOT); /* change back to root */
1017 * Close all open files (except std*) and turn off core dumps.
1022 int miss[3], devnull = -1;
1023 #if defined(__linux__) || (defined(RLIMIT_CORE) && !defined(SUDO_DEVEL))
1027 #if defined(__linux__)
1029 * Unlimit the number of processes since Linux's setuid() will
1030 * apply resource limits when changing uid and return EAGAIN if
1031 * nproc would be violated by the uid switch.
1033 rl.rlim_cur = rl.rlim_max = RLIM_INFINITY;
1034 if (setrlimit(RLIMIT_NPROC, &rl)) {
1035 if (getrlimit(RLIMIT_NPROC, &rl) == 0) {
1036 rl.rlim_cur = rl.rlim_max;
1037 (void)setrlimit(RLIMIT_NPROC, &rl);
1040 #endif /* __linux__ */
1041 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
1043 * Turn off core dumps.
1045 (void) getrlimit(RLIMIT_CORE, &corelimit);
1046 memcpy(&rl, &corelimit, sizeof(struct rlimit));
1048 (void) setrlimit(RLIMIT_CORE, &rl);
1049 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
1052 * stdin, stdout and stderr must be open; set them to /dev/null
1053 * if they are closed and close all other fds.
1055 miss[STDIN_FILENO] = fcntl(STDIN_FILENO, F_GETFL, 0) == -1;
1056 miss[STDOUT_FILENO] = fcntl(STDOUT_FILENO, F_GETFL, 0) == -1;
1057 miss[STDERR_FILENO] = fcntl(STDERR_FILENO, F_GETFL, 0) == -1;
1058 if (miss[STDIN_FILENO] || miss[STDOUT_FILENO] || miss[STDERR_FILENO]) {
1059 if ((devnull = open(_PATH_DEVNULL, O_RDWR, 0644)) != -1) {
1060 if (miss[STDIN_FILENO])
1061 (void) dup2(devnull, STDIN_FILENO);
1062 if (miss[STDOUT_FILENO])
1063 (void) dup2(devnull, STDOUT_FILENO);
1064 if (miss[STDERR_FILENO])
1065 (void) dup2(devnull, STDERR_FILENO);
1068 closefrom(STDERR_FILENO + 1);
1071 #ifdef HAVE_LOGIN_CAP_H
1079 * Don't make it a fatal error if the user didn't specify the login
1080 * class themselves. We do this because if login.conf gets
1081 * corrupted we want the admin to be able to use sudo to fix it.
1084 errflags = NO_MAIL|MSG_ONLY;
1086 errflags = NO_MAIL|MSG_ONLY|NO_EXIT;
1088 if (login_class && strcmp(login_class, "-") != 0) {
1089 if (strcmp(*user_runas, "root") != 0 && user_uid != 0)
1090 errx(1, "only root can use -c %s", login_class);
1092 login_class = pw->pw_class;
1093 if (!login_class || !*login_class)
1095 (pw->pw_uid == 0) ? LOGIN_DEFROOTCLASS : LOGIN_DEFCLASS;
1098 lc = login_getclass(login_class);
1099 if (!lc || !lc->lc_class || strcmp(lc->lc_class, login_class) != 0) {
1100 log_error(errflags, "unknown login class: %s", login_class);
1102 lc = login_getclass(NULL); /* needed for login_getstyle() later */
1111 #endif /* HAVE_LOGIN_CAP_H */
1113 #ifdef HAVE_PROJECT_H
1118 int errflags = NO_MAIL|MSG_ONLY|NO_EXIT;
1120 struct project proj;
1121 struct project *resultp = '\0';
1125 * Collect the default project for the user and settaskid
1128 if (resultp = getdefaultproj(pw->pw_name, &proj, buf, sizeof(buf))) {
1129 errval = setproject(resultp->pj_name, pw->pw_name, TASK_NORMAL);
1132 case SETPROJ_ERR_TASK:
1133 if (errno == EAGAIN)
1134 log_error(errflags, "resource control limit has been reached");
1135 else if (errno == ESRCH)
1136 log_error(errflags, "user \"%s\" is not a member of "
1137 "project \"%s\"", pw->pw_name, resultp->pj_name);
1138 else if (errno == EACCES)
1139 log_error(errflags, "the invoking task is final");
1141 log_error(errflags, "could not join project \"%s\"",
1144 case SETPROJ_ERR_POOL:
1145 if (errno == EACCES)
1146 log_error(errflags, "no resource pool accepting "
1147 "default bindings exists for project \"%s\"",
1149 else if (errno == ESRCH)
1150 log_error(errflags, "specified resource pool does "
1151 "not exist for project \"%s\"", resultp->pj_name);
1153 log_error(errflags, "could not bind to default "
1154 "resource pool for project \"%s\"", resultp->pj_name);
1158 log_error(errflags, "setproject failed for project \"%s\"",
1161 log_error(errflags, "warning, resource control assignment "
1162 "failed for project \"%s\"", resultp->pj_name);
1167 log_error(errflags, "getdefaultproj() error: %s", strerror(errno));
1177 #endif /* HAVE_PROJECT_H */
1180 * Look up the fully qualified domain name and set user_host and user_shost.
1185 #ifdef HAVE_GETADDRINFO
1186 struct addrinfo *res0, hint;
1192 #ifdef HAVE_GETADDRINFO
1193 memset(&hint, 0, sizeof(hint));
1194 hint.ai_family = PF_UNSPEC;
1195 hint.ai_flags = AI_CANONNAME;
1196 if (getaddrinfo(user_host, NULL, &hint, &res0) != 0) {
1198 if (!(hp = gethostbyname(user_host))) {
1200 log_error(MSG_ONLY|NO_EXIT,
1201 "unable to resolve host %s", user_host);
1203 if (user_shost != user_host)
1206 #ifdef HAVE_GETADDRINFO
1207 user_host = estrdup(res0->ai_canonname);
1210 user_host = estrdup(hp->h_name);
1213 if ((p = strchr(user_host, '.'))) {
1215 user_shost = estrdup(user_host);
1218 user_shost = user_host;
1223 * Get passwd entry for the user we are going to run commands as.
1224 * By default, this is "root". Updates runas_pw as a side effect.
1230 if (runas_pw != NULL) {
1231 if (user_runas != &def_runas_default)
1232 return(TRUE); /* don't override -u option */
1236 runas_pw = sudo_getpwuid(atoi(user + 1));
1237 if (runas_pw == NULL) {
1238 runas_pw = emalloc(sizeof(struct passwd));
1239 (void) memset((VOID *)runas_pw, 0, sizeof(struct passwd));
1240 runas_pw->pw_uid = atoi(user + 1);
1243 runas_pw = sudo_getpwnam(user);
1244 if (runas_pw == NULL)
1245 log_error(NO_MAIL|MSG_ONLY, "no passwd entry for %s!", user);
1251 * Get passwd entry for the user we are going to authenticate as.
1252 * By default, this is the user invoking sudo. In the most common
1253 * case, this matches sudo_user.pw or runas_pw.
1255 static struct passwd *
1261 if (runas_pw->pw_uid == 0)
1263 else if ((pw = sudo_getpwuid(0)) == NULL)
1264 log_error(0, "uid 0 does not exist in the passwd file!");
1265 } else if (def_runaspw) {
1266 if (strcmp(def_runas_default, *user_runas) == 0)
1268 else if ((pw = sudo_getpwnam(def_runas_default)) == NULL)
1269 log_error(0, "user %s does not exist in the passwd file!",
1271 } else if (def_targetpw) {
1272 if (runas_pw->pw_name == NULL)
1273 log_error(NO_MAIL|MSG_ONLY, "no passwd entry for %lu!",
1274 (unsigned long) runas_pw->pw_uid);
1283 * Tell which options are mutually exclusive and exit.
1286 usage_excl(exit_val)
1289 warnx("Only one of the -e, -h, i, -k, -K, -l, -s, -v or -V options may be used");
1294 * Give usage message and exit.
1300 char **p, **uvec[4];
1301 int i, linelen, linemax, ulen, plen;
1302 static char *uvec1[] = {
1312 static char *uvec2[] = {
1314 #ifdef HAVE_BSD_AUTH_H
1317 #ifdef HAVE_LOGIN_CAP_H
1327 " [-u username|#uid]",
1329 " {-i | -s | <command>}",
1332 static char *uvec3[] = {
1335 #ifdef HAVE_BSD_AUTH_H
1338 #ifdef HAVE_LOGIN_CAP_H
1342 " [-u username|#uid]",
1348 * Use usage vectors appropriate to the progname.
1350 if (strcmp(getprogname(), "sudoedit") == 0) {
1351 uvec[0] = uvec3 + 1;
1361 * Print usage and wrap lines as needed.
1362 * Assumes an 80-character wide terminal, which is kind of bogus...
1364 ulen = (int)strlen(getprogname()) + 7;
1366 for (i = 0; uvec[i] != NULL; i++) {
1367 printf("usage: %s", getprogname());
1368 linelen = linemax - ulen;
1369 for (p = uvec[i]; *p != NULL; p++) {
1370 plen = (int)strlen(*p);
1371 if (linelen >= plen || linelen == linemax - ulen) {
1376 linelen = linemax - ulen;
1377 printf("\n%*s", ulen, "");