2 * Copyright (c) 1993-1996, 1998-2008 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 */
67 #if TIME_WITH_SYS_TIME
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 <sys/task.h>
95 # include <selinux/selinux.h>
99 #include "sudo_usage.h"
101 #include "interfaces.h"
105 __unused static const char rcsid[] = "$Sudo: sudo.c,v 1.500 2008/11/18 15:57:09 millert Exp $";
111 static void init_vars __P((int, char **));
112 static int set_cmnd __P((int));
113 static int parse_args __P((int, char **));
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 set_runasgr __P((char *));
118 static void set_runaspw __P((char *));
119 static void show_version __P((void));
120 static void usage __P((int))
121 __attribute__((__noreturn__));
122 static void usage_excl __P((int))
123 __attribute__((__noreturn__));
124 static struct passwd *get_authpw __P((void));
125 extern int sudo_edit __P((int, char **, char **));
126 extern void rebuild_env __P((int, int));
127 void validate_env_vars __P((struct list_member *));
128 void insert_env_vars __P((struct list_member *));
134 char **Argv, **NewArgv;
136 static int user_closefrom = -1;
137 struct sudo_user sudo_user;
138 struct passwd *auth_pw, *list_pw;
139 struct interface *interfaces;
144 extern int errorlineno;
145 extern int parse_error;
146 extern char *errorfile;
147 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
148 static struct rlimit corelimit;
149 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
150 #ifdef HAVE_LOGIN_CAP_H
152 #endif /* HAVE_LOGIN_CAP_H */
153 #ifdef HAVE_BSD_AUTH_H
155 #endif /* HAVE_BSD_AUTH_H */
156 sigaction_t saved_sa_int, saved_sa_quit, saved_sa_tstp;
157 static char *runas_user;
158 static char *runas_group;
159 static struct sudo_nss_list *snl;
166 main(argc, argv, envp)
171 int sources = 0, validated;
172 int fd, cmnd_status, sudo_mode, pwflag, rc = 0;
174 struct sudo_nss *nss;
175 #if defined(SUDO_DEVEL) && defined(__OpenBSD__)
176 extern char *malloc_options;
177 malloc_options = "AFGJPR";
180 #ifdef HAVE_SETLOCALE
181 setlocale(LC_ALL, "");
185 if ((Argc = argc) < 1)
188 /* Must be done as the first thing... */
189 #if defined(HAVE_GETPRPWNAM) && defined(HAVE_SET_AUTH_PARAMETERS)
190 (void) set_auth_parameters(Argc, Argv);
191 # ifdef HAVE_INITPRIVS
194 #endif /* HAVE_GETPRPWNAM && HAVE_SET_AUTH_PARAMETERS */
197 errorx(1, "must be setuid root");
201 * Ignore keyboard-generated signals so the user cannot interrupt
202 * us at some point and avoid the logging.
203 * Install handler to wait for children when they exit.
205 zero_bytes(&sa, sizeof(sa));
206 sigemptyset(&sa.sa_mask);
207 sa.sa_flags = SA_RESTART;
208 sa.sa_handler = SIG_IGN;
209 (void) sigaction(SIGINT, &sa, &saved_sa_int);
210 (void) sigaction(SIGQUIT, &sa, &saved_sa_quit);
211 (void) sigaction(SIGTSTP, &sa, &saved_sa_tstp);
214 * Turn off core dumps and make sure fds 0-2 are open.
220 /* Parse our arguments. */
221 sudo_mode = parse_args(Argc, Argv);
223 /* Setup defaults data structures. */
226 /* Load the list of local ip addresses and netmasks. */
230 if (ISSET(sudo_mode, MODE_SHELL))
232 else if (ISSET(sudo_mode, MODE_EDIT))
233 user_cmnd = "sudoedit";
243 user_cmnd = "validate";
247 case MODE_INVALIDATE:
264 /* Must have a command to run... */
265 if (user_cmnd == NULL && NewArgc == 0)
268 init_vars(sudo_mode, envp); /* XXX - move this later? */
270 /* Parse nsswitch.conf for sudoers order. */
271 snl = sudo_read_nss();
273 /* Open and parse sudoers, set global defaults */
274 tq_foreach_fwd(snl, nss) {
275 if (nss->open(nss) == 0 && nss->parse(nss) == 0) {
281 log_error(0, "no valid sudoers sources found, quitting");
283 /* XXX - collect post-sudoers parse settings into a function */
286 * Set runas passwd/group entries based on command line or sudoers.
287 * Note that if runas_group was specified without runas_user we
288 * defer setting runas_pw so the match routines know to ignore it.
290 if (runas_group != NULL) {
291 set_runasgr(runas_group);
292 if (runas_user != NULL)
293 set_runaspw(runas_user);
295 set_runaspw(runas_user ? runas_user : def_runas_default);
297 if (!update_defaults(SETDEF_RUNAS))
298 log_error(NO_STDERR|NO_EXIT, "problem with defaults entries");
300 /* Set login class if applicable. */
301 set_loginclass(sudo_user.pw);
303 /* Update initial shell now that runas is set. */
304 if (ISSET(sudo_mode, MODE_LOGIN_SHELL))
305 NewArgv[0] = runas_pw->pw_shell;
307 /* This goes after sudoers is parsed since it may have timestamp options. */
308 if (sudo_mode == MODE_KILL || sudo_mode == MODE_INVALIDATE) {
309 remove_timestamp((sudo_mode == MODE_KILL));
314 /* Is root even allowed to run sudo? */
315 if (user_uid == 0 && !def_root_sudo) {
316 (void) fprintf(stderr,
317 "Sorry, %s has been configured to not allow root to run it.\n",
322 /* Check for -C overriding def_closefrom. */
323 if (user_closefrom >= 0 && user_closefrom != def_closefrom) {
324 if (!def_closefrom_override)
325 errorx(1, "you are not permitted to use the -C option");
327 def_closefrom = user_closefrom;
330 cmnd_status = set_cmnd(sudo_mode);
332 #ifdef HAVE_SETLOCALE
333 if (!setlocale(LC_ALL, def_sudoers_locale)) {
334 warningx("unable to set locale to \"%s\", using \"C\"",
336 setlocale(LC_ALL, "C");
340 validated = FLAG_NO_USER | FLAG_NO_HOST;
341 tq_foreach_fwd(snl, nss) {
342 validated = nss->lookup(nss, validated, pwflag);
344 /* Handle [NOTFOUND=return] */
345 if (!ISSET(validated, VALIDATE_OK) && nss->ret_notfound)
348 if (safe_cmnd == NULL)
349 safe_cmnd = estrdup(user_cmnd);
351 #ifdef HAVE_SETLOCALE
352 setlocale(LC_ALL, "");
355 /* If only a group was specified, set runas_pw based on invoking user. */
356 if (runas_pw == NULL)
357 set_runaspw(user_name);
360 * Look up the timestamp dir owner if one is specified.
362 if (def_timestampowner) {
365 if (*def_timestampowner == '#')
366 pw = sudo_getpwuid(atoi(def_timestampowner + 1));
368 pw = sudo_getpwnam(def_timestampowner);
370 log_error(0, "timestamp owner (%s): No such user",
372 timestamp_uid = pw->pw_uid;
375 /* If given the -P option, set the "preserve_groups" flag. */
376 if (ISSET(sudo_mode, MODE_PRESERVE_GROUPS))
377 def_preserve_groups = TRUE;
379 /* If no command line args and "set_home" is not set, error out. */
380 if (ISSET(sudo_mode, MODE_IMPLIED_SHELL) && !def_shell_noargs)
383 /* Bail if a tty is required and we don't have one. */
384 if (def_requiretty) {
385 if ((fd = open(_PATH_TTY, O_RDWR|O_NOCTTY)) == -1)
386 log_error(NO_MAIL, "sorry, you must have a tty to run sudo");
391 /* Use askpass value from sudoers unless user specified their own. */
392 if (def_askpass && !user_askpass)
393 user_askpass = def_askpass;
395 /* User may have overridden environment resetting via the -E flag. */
396 if (ISSET(sudo_mode, MODE_PRESERVE_ENV) && def_setenv)
397 def_env_reset = FALSE;
399 /* Build a new environment that avoids any nasty bits. */
400 rebuild_env(sudo_mode, def_noexec);
402 /* Fill in passwd struct based on user we are authenticating as. */
403 auth_pw = get_authpw();
405 /* Require a password if sudoers says so. */
406 if (def_authenticate)
407 check_user(validated, !ISSET(sudo_mode, MODE_NONINTERACTIVE));
409 /* If run as root with SUDO_USER set, set sudo_user.pw to that user. */
410 /* XXX - causes confusion when root is not listed in sudoers */
411 if (sudo_mode & (MODE_RUN | MODE_EDIT) && prev_user != NULL) {
412 if (user_uid == 0 && strcmp(prev_user, "root") != 0) {
415 if ((pw = sudo_getpwnam(prev_user)) != NULL)
420 if (ISSET(validated, VALIDATE_OK)) {
421 /* Finally tell the user if the command did not exist. */
422 if (cmnd_status == NOT_FOUND_DOT)
423 errorx(1, "ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run.", user_cmnd, user_cmnd, user_cmnd);
424 else if (cmnd_status == NOT_FOUND)
425 errorx(1, "%s: command not found", user_cmnd);
427 /* If user specified env vars make sure sudoers allows it. */
428 if (ISSET(sudo_mode, MODE_RUN) && !def_setenv) {
429 if (ISSET(sudo_mode, MODE_PRESERVE_ENV))
431 "sorry, you are not allowed to preserve the environment");
433 validate_env_vars(sudo_user.env_vars);
436 log_allowed(validated);
437 if (sudo_mode == MODE_CHECK)
438 rc = display_cmnd(snl, list_pw ? list_pw : sudo_user.pw);
439 else if (sudo_mode == MODE_LIST)
440 display_privs(snl, list_pw ? list_pw : sudo_user.pw);
442 /* Cleanup sudoers sources */
443 tq_foreach_fwd(snl, nss)
446 /* Deferred exit due to sudo_ldap_close() */
447 if (sudo_mode == MODE_VALIDATE || sudo_mode == MODE_CHECK ||
448 sudo_mode == MODE_LIST)
452 * Override user's umask if configured to do so.
453 * If user's umask is more restrictive, OR in those bits too.
455 if (def_umask != 0777) {
456 mode_t mask = umask(def_umask);
458 if (mask != def_umask)
462 /* Restore coredumpsize resource limit. */
463 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
464 (void) setrlimit(RLIMIT_CORE, &corelimit);
465 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
467 /* Become specified user or root if executing a command. */
468 if (ISSET(sudo_mode, MODE_RUN))
469 set_perms(PERM_FULL_RUNAS);
471 if (ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
474 /* Convert /bin/sh -> -sh so shell knows it is a login shell */
475 if ((p = strrchr(NewArgv[0], '/')) == NULL)
480 /* Change to target user's homedir. */
481 if (chdir(runas_pw->pw_dir) == -1)
482 warning("unable to change directory to %s", runas_pw->pw_dir);
484 #if defined(__linux__) || defined(_AIX)
485 /* Insert system-wide environment variables. */
486 read_env_file(_PATH_ENVIRONMENT, TRUE);
490 if (ISSET(sudo_mode, MODE_EDIT))
491 exit(sudo_edit(NewArgc, NewArgv, envp));
493 /* Insert system-wide environment variables. */
495 read_env_file(def_env_file, FALSE);
497 /* Insert user-specified environment variables. */
498 insert_env_vars(sudo_user.env_vars);
500 /* Restore signal handlers before we exec. */
501 (void) sigaction(SIGINT, &saved_sa_int, NULL);
502 (void) sigaction(SIGQUIT, &saved_sa_quit, NULL);
503 (void) sigaction(SIGTSTP, &saved_sa_tstp, NULL);
505 /* Close the password and group files and free up memory. */
509 closefrom(def_closefrom + 1);
512 if (ISSET(sudo_mode, MODE_BACKGROUND) && fork() > 0)
516 if (is_selinux_enabled() > 0 && user_role != NULL)
517 selinux_exec(user_role, user_type, NewArgv,
518 ISSET(sudo_mode, MODE_LOGIN_SHELL));
520 execv(safe_cmnd, NewArgv);
524 #endif /* PROFILING */
526 * If we got here then execve() failed...
528 if (errno == ENOEXEC) {
529 NewArgv--; /* at least one extra slot... */
531 NewArgv[1] = safe_cmnd;
532 execv(_PATH_BSHELL, NewArgv);
533 } warning("unable to execute %s", safe_cmnd);
535 } else if (ISSET(validated, FLAG_NO_USER | FLAG_NO_HOST)) {
536 log_denial(validated, 1);
541 * We'd like to not leak path info at all here, but that can
542 * *really* confuse the users. To really close the leak we'd
543 * have to say "not allowed to run foo" even when the problem
544 * is just "no foo in path" since the user can trivially set
545 * their path to just contain a single dir.
547 log_denial(validated,
548 !(cmnd_status == NOT_FOUND_DOT || cmnd_status == NOT_FOUND));
549 if (cmnd_status == NOT_FOUND)
550 warningx("%s: command not found", user_cmnd);
551 else if (cmnd_status == NOT_FOUND_DOT)
552 warningx("ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run.", user_cmnd, user_cmnd, user_cmnd);
554 /* Just tell the user they are not allowed to run foo. */
555 log_denial(validated, 1);
559 exit(0); /* not reached */
563 * Initialize timezone, set umask, fill in ``sudo_user'' struct and
564 * load the ``interfaces'' array.
567 init_vars(sudo_mode, envp)
571 char *p, **ep, thost[MAXHOSTNAMELEN + 1];
574 /* Sanity check command from user. */
575 if (user_cmnd == NULL && strlen(NewArgv[0]) >= PATH_MAX)
576 errorx(1, "%s: File name too long", NewArgv[0]);
579 (void) tzset(); /* set the timezone if applicable */
580 #endif /* HAVE_TZSET */
582 /* Default value for cmnd and cwd, overridden later. */
583 if (user_cmnd == NULL)
584 user_cmnd = NewArgv[0];
585 (void) strlcpy(user_cwd, "unknown", sizeof(user_cwd));
588 * We avoid gethostbyname() if possible since we don't want
589 * sudo to block if DNS or NIS is hosed.
590 * "host" is the (possibly fully-qualified) hostname and
591 * "shost" is the unqualified form of the hostname.
593 sudo_user.host_fqdn_queried = FALSE;
594 nohostname = gethostname(thost, sizeof(thost));
596 user_host = user_shost = "localhost";
598 thost[sizeof(thost) - 1] = '\0';
599 user_host = estrdup(thost);
601 /* Defer call to set_fqdn() until log_error() is safe. */
602 user_shost = user_host;
604 user_shost = user_host;
608 if ((p = ttyname(STDIN_FILENO)) || (p = ttyname(STDOUT_FILENO))) {
609 user_tty = user_ttypath = estrdup(p);
610 if (strncmp(user_tty, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
611 user_tty += sizeof(_PATH_DEV) - 1;
613 user_tty = "unknown";
615 for (ep = envp; *ep; ep++) {
616 /* XXX - don't fill in if empty string */
619 if (strncmp("DISPLAY=", *ep, 8) == 0)
620 user_display = *ep + 8;
623 if (strncmp("KRB5CCNAME=", *ep, 11) == 0)
624 user_ccname = *ep + 11;
627 if (strncmp("PATH=", *ep, 5) == 0)
631 if (strncmp("SHELL=", *ep, 6) == 0)
632 user_shell = *ep + 6;
633 else if (!user_prompt && strncmp("SUDO_PROMPT=", *ep, 12) == 0)
634 user_prompt = *ep + 12;
635 else if (strncmp("SUDO_USER=", *ep, 10) == 0)
636 prev_user = *ep + 10;
637 else if (strncmp("SUDO_ASKPASS=", *ep, 13) == 0)
638 user_askpass = *ep + 13;
644 * Get a local copy of the user's struct passwd with the shadow password
645 * if necessary. It is assumed that euid is 0 at this point so we
646 * can read the shadow passwd file if necessary.
648 if ((sudo_user.pw = sudo_getpwuid(getuid())) == NULL) {
649 /* Need to make a fake struct passwd for logging to work. */
651 char pw_name[MAX_UID_T_LEN + 1];
653 pw.pw_uid = getuid();
654 (void) snprintf(pw_name, sizeof(pw_name), "%lu",
655 (unsigned long) pw.pw_uid);
656 pw.pw_name = pw_name;
660 * If we are in -k/-K mode, just spew to stderr. It is not unusual for
661 * users to place "sudo -k" in a .logout file which can cause sudo to
662 * be run during reboot after the YP/NIS/NIS+/LDAP/etc daemon has died.
664 if (sudo_mode & (MODE_INVALIDATE|MODE_KILL))
665 errorx(1, "unknown uid: %s", pw_name);
666 log_error(0, "unknown uid: %s", pw_name);
668 if (user_shell == NULL || *user_shell == '\0')
669 user_shell = estrdup(sudo_user.pw->pw_shell);
671 /* It is now safe to use log_error() and set_perms() */
673 #ifdef HAVE_GETGROUPS
674 if ((user_ngroups = getgroups(0, NULL)) > 0) {
675 user_groups = emalloc2(user_ngroups, sizeof(GETGROUPS_T));
676 if (getgroups(user_ngroups, user_groups) < 0)
677 log_error(USE_ERRNO|MSG_ONLY, "can't get group vector");
683 set_fqdn(); /* may call log_error() */
686 log_error(USE_ERRNO|MSG_ONLY, "can't get hostname");
689 * Get current working directory. Try as user, fall back to root.
691 set_perms(PERM_USER);
692 if (!getcwd(user_cwd, sizeof(user_cwd))) {
693 set_perms(PERM_ROOT);
694 if (!getcwd(user_cwd, sizeof(user_cwd))) {
695 warningx("cannot get working directory");
696 (void) strlcpy(user_cwd, "unknown", sizeof(user_cwd));
699 set_perms(PERM_ROOT);
702 * If we were given the '-e', '-i' or '-s' options we need to redo
703 * NewArgv and NewArgc.
705 if (ISSET(sudo_mode, MODE_EDIT)) {
708 NewArgv[0] = "sudoedit";
709 } else if (ISSET(sudo_mode, MODE_SHELL)) {
712 /* Allocate an extra slot for execve() failure (ENOEXEC). */
713 av = (char **) emalloc2(5, sizeof(char *));
716 av[0] = user_shell; /* may be updated later */
719 char *cmnd, *src, *dst, *end;
720 size = (size_t) (NewArgv[NewArgc - 1] - NewArgv[0]) +
721 strlen(NewArgv[NewArgc - 1]) + 1;
722 cmnd = emalloc(size);
725 for (end = src + size - 1; src < end; src++, dst++)
726 *dst = *src == 0 ? ' ' : *src;
732 av[++NewArgc] = NULL;
738 * Fill in user_cmnd, user_args, user_base and user_stat variables
739 * and apply any command-specific defaults entries.
747 /* Set project if applicable. */
748 set_project(runas_pw);
750 /* Resolve the path and return. */
752 user_stat = emalloc(sizeof(struct stat));
753 if (sudo_mode & (MODE_RUN | MODE_EDIT | MODE_CHECK)) {
754 if (ISSET(sudo_mode, MODE_RUN | MODE_CHECK)) {
755 set_perms(PERM_RUNAS);
756 rval = find_path(NewArgv[0], &user_cmnd, user_stat, user_path);
757 set_perms(PERM_ROOT);
759 /* Failed as root, try as invoking user. */
760 set_perms(PERM_USER);
761 rval = find_path(NewArgv[0], &user_cmnd, user_stat, user_path);
762 set_perms(PERM_ROOT);
771 /* If we didn't realloc NewArgv it is contiguous so just count. */
772 if (!ISSET(sudo_mode, MODE_SHELL)) {
773 size = (size_t) (NewArgv[NewArgc-1] - NewArgv[1]) +
774 strlen(NewArgv[NewArgc-1]) + 1;
776 for (size = 0, from = NewArgv + 1; *from; from++)
777 size += strlen(*from) + 1;
780 /* Alloc and build up user_args. */
781 user_args = (char *) emalloc(size);
782 for (to = user_args, from = NewArgv + 1; *from; from++) {
783 n = strlcpy(to, *from, size - (to - user_args));
784 if (n >= size - (to - user_args))
785 errorx(1, "internal error, init_vars() overflow");
792 if ((user_base = strrchr(user_cmnd, '/')) != NULL)
795 user_base = user_cmnd;
797 if (!update_defaults(SETDEF_CMND))
798 log_error(NO_STDERR|NO_EXIT, "problem with defaults entries");
804 * Command line argument parsing.
805 * Sets NewArgc and NewArgv which corresponds to the argc/argv we'll use
806 * for the command to be run (if we are running one).
809 parse_args(argc, argv)
813 int mode = 0; /* what mode is sudo to be run in? */
814 int flags = 0; /* mode flags */
817 /* First, check to see if we were invoked as "sudoedit". */
818 if (strcmp(getprogname(), "sudoedit") == 0)
821 /* Returns true if the last option string was "--" */
822 #define got_end_of_args (optind > 1 && argv[optind - 1][0] == '-' && \
823 argv[optind - 1][1] == '-' && argv[optind - 1][2] == '\0')
825 /* Returns true if next option is an environment variable */
826 #define is_envar (optind < argc && argv[optind][0] != '/' && \
827 strchr(argv[optind], '=') != NULL)
831 * We disable arg permutation for GNU getopt().
832 * Some trickiness is required to allow environment variables
833 * to be interspersed with command line options.
835 if ((ch = getopt(argc, argv, "+Aa:bC:c:Eeg:HhiKkLlnPp:r:Sst:U:u:Vv")) != -1) {
838 SET(tgetpass_flags, TGP_ASKPASS);
840 #ifdef HAVE_BSD_AUTH_H
842 login_style = optarg;
846 SET(flags, MODE_BACKGROUND);
849 if ((user_closefrom = atoi(optarg)) < 3) {
850 warningx("the argument to -C must be at least 3");
854 #ifdef HAVE_LOGIN_CAP_H
856 login_class = optarg;
857 def_use_loginclass = TRUE;
861 SET(flags, MODE_PRESERVE_ENV);
864 if (mode && mode != MODE_EDIT)
869 runas_group = optarg;
872 SET(flags, MODE_RESET_HOME);
875 if (mode && mode != MODE_HELP)
880 SET(flags, MODE_LOGIN_SHELL);
881 def_env_reset = TRUE;
884 if (mode && mode != MODE_INVALIDATE)
886 mode = MODE_INVALIDATE;
889 if (mode && mode != MODE_KILL)
894 if (mode && mode != MODE_LISTDEFS)
896 mode = MODE_LISTDEFS;
900 if (mode == MODE_LIST)
908 SET(flags, MODE_NONINTERACTIVE);
911 SET(flags, MODE_PRESERVE_GROUPS);
914 user_prompt = optarg;
915 def_passprompt_override = TRUE;
926 SET(tgetpass_flags, TGP_STDIN);
929 SET(flags, MODE_SHELL);
932 if ((list_pw = sudo_getpwnam(optarg)) == NULL)
933 errorx(1, "unknown user: %s", optarg);
939 if (mode && mode != MODE_VALIDATE)
941 mode = MODE_VALIDATE;
944 if (mode && mode != MODE_VERSION)
951 } else if (!got_end_of_args && is_envar) {
952 struct list_member *ev;
954 /* Store environment variable. */
955 ev = emalloc(sizeof(*ev));
956 ev->value = argv[optind];
957 ev->next = sudo_user.env_vars;
958 sudo_user.env_vars = ev;
960 /* Crank optind and resume getopt. */
963 /* Not an option or an environment variable -- we're done. */
968 NewArgc = argc - optind;
969 NewArgv = argv + optind;
974 if (NewArgc > 0 && mode == MODE_LIST)
977 if (ISSET(flags, MODE_LOGIN_SHELL)) {
978 if (ISSET(flags, MODE_SHELL)) {
979 warningx("you may not specify both the `-i' and `-s' options");
982 if (ISSET(flags, MODE_PRESERVE_ENV)) {
983 warningx("you may not specify both the `-i' and `-E' options");
986 SET(flags, MODE_SHELL);
988 if (mode == MODE_EDIT &&
989 (ISSET(flags, MODE_PRESERVE_ENV) || sudo_user.env_vars != NULL)) {
990 if (ISSET(mode, MODE_PRESERVE_ENV))
991 warningx("the `-E' option is not valid in edit mode");
992 if (sudo_user.env_vars != NULL)
993 warningx("you may not specify environment variables in edit mode");
996 if ((runas_user != NULL || runas_group != NULL) &&
997 !ISSET(mode, MODE_EDIT | MODE_RUN | MODE_CHECK)) {
1000 if (list_pw != NULL && mode != MODE_LIST && mode != MODE_CHECK) {
1001 warningx("the `-U' option may only be used with the `-l' option");
1004 if (ISSET(tgetpass_flags, TGP_STDIN) && ISSET(tgetpass_flags, TGP_ASKPASS)) {
1005 warningx("the `-A' and `-S' options may not be used together");
1008 if ((NewArgc == 0 && mode == MODE_EDIT) ||
1009 (NewArgc > 0 && !ISSET(mode, MODE_RUN | MODE_EDIT | MODE_CHECK)))
1011 if (NewArgc == 0 && mode == MODE_RUN && !ISSET(flags, MODE_SHELL))
1012 SET(flags, (MODE_IMPLIED_SHELL | MODE_SHELL));
1014 return(mode | flags);
1018 * Open sudoers and sanity check mode/owner/type.
1019 * Returns a handle to the sudoers file or NULL on error.
1022 open_sudoers(sudoers, keepopen)
1023 const char *sudoers;
1026 struct stat statbuf;
1031 * Fix the mode and group on sudoers file from old default.
1032 * Only works if file system is readable/writable by root.
1034 if ((rootstat = stat_sudoers(sudoers, &statbuf)) == 0 &&
1035 SUDOERS_UID == statbuf.st_uid && SUDOERS_MODE != 0400 &&
1036 (statbuf.st_mode & 0007777) == 0400) {
1038 if (chmod(sudoers, SUDOERS_MODE) == 0) {
1039 warningx("fixed mode on %s", sudoers);
1040 SET(statbuf.st_mode, SUDOERS_MODE);
1041 if (statbuf.st_gid != SUDOERS_GID) {
1042 if (chown(sudoers, (uid_t) -1, SUDOERS_GID) == 0) {
1043 warningx("set group on %s", sudoers);
1044 statbuf.st_gid = SUDOERS_GID;
1046 warning("unable to set group on %s", sudoers);
1049 warning("unable to fix mode on %s", sudoers);
1053 * Sanity checks on sudoers file. Must be done as sudoers
1054 * file owner. We already did a stat as root, so use that
1055 * data if we can't stat as sudoers file owner.
1057 set_perms(PERM_SUDOERS);
1059 if (rootstat != 0 && stat_sudoers(sudoers, &statbuf) != 0)
1060 log_error(USE_ERRNO|NO_EXIT, "can't stat %s", sudoers);
1061 else if (!S_ISREG(statbuf.st_mode))
1062 log_error(NO_EXIT, "%s is not a regular file", sudoers);
1063 else if ((statbuf.st_mode & 07777) != SUDOERS_MODE)
1064 log_error(NO_EXIT, "%s is mode 0%o, should be 0%o", sudoers,
1065 (unsigned int) (statbuf.st_mode & 07777),
1066 (unsigned int) SUDOERS_MODE);
1067 else if (statbuf.st_uid != SUDOERS_UID)
1068 log_error(NO_EXIT, "%s is owned by uid %lu, should be %lu", sudoers,
1069 (unsigned long) statbuf.st_uid, (unsigned long) SUDOERS_UID);
1070 else if (statbuf.st_gid != SUDOERS_GID)
1071 log_error(NO_EXIT, "%s is owned by gid %lu, should be %lu", sudoers,
1072 (unsigned long) statbuf.st_gid, (unsigned long) SUDOERS_GID);
1073 else if ((fp = fopen(sudoers, "r")) == NULL)
1074 log_error(USE_ERRNO, "can't open %s", sudoers);
1075 else if (statbuf.st_size != 0) {
1077 * Make sure we can actually read sudoers so we can present the
1078 * user with a reasonable error message.
1080 if (fgetc(fp) == EOF)
1081 log_error(USE_ERRNO, "can't read %s", sudoers);
1084 (void) fcntl(fileno(fp), F_SETFD, 1);
1086 set_perms(PERM_ROOT); /* change back to root */
1091 * Close all open files (except std*) and turn off core dumps.
1092 * Also sets the set_perms() pointer to the correct function.
1097 int miss[3], devnull = -1;
1098 #if defined(__linux__) || (defined(RLIMIT_CORE) && !defined(SUDO_DEVEL))
1102 #if defined(__linux__)
1104 * Unlimit the number of processes since Linux's setuid() will
1105 * apply resource limits when changing uid and return EAGAIN if
1106 * nproc would be violated by the uid switch.
1108 rl.rlim_cur = rl.rlim_max = RLIM_INFINITY;
1109 if (setrlimit(RLIMIT_NPROC, &rl)) {
1110 if (getrlimit(RLIMIT_NPROC, &rl) == 0) {
1111 rl.rlim_cur = rl.rlim_max;
1112 (void)setrlimit(RLIMIT_NPROC, &rl);
1115 #endif /* __linux__ */
1116 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
1118 * Turn off core dumps.
1120 (void) getrlimit(RLIMIT_CORE, &corelimit);
1121 memcpy(&rl, &corelimit, sizeof(struct rlimit));
1123 (void) setrlimit(RLIMIT_CORE, &rl);
1124 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
1127 * stdin, stdout and stderr must be open; set them to /dev/null
1128 * if they are closed and close all other fds.
1130 miss[STDIN_FILENO] = fcntl(STDIN_FILENO, F_GETFL, 0) == -1;
1131 miss[STDOUT_FILENO] = fcntl(STDOUT_FILENO, F_GETFL, 0) == -1;
1132 miss[STDERR_FILENO] = fcntl(STDERR_FILENO, F_GETFL, 0) == -1;
1133 if (miss[STDIN_FILENO] || miss[STDOUT_FILENO] || miss[STDERR_FILENO]) {
1134 if ((devnull = open(_PATH_DEVNULL, O_RDWR, 0644)) != -1) {
1135 if (miss[STDIN_FILENO])
1136 (void) dup2(devnull, STDIN_FILENO);
1137 if (miss[STDOUT_FILENO])
1138 (void) dup2(devnull, STDOUT_FILENO);
1139 if (miss[STDERR_FILENO])
1140 (void) dup2(devnull, STDERR_FILENO);
1141 if (devnull > STDERR_FILENO)
1147 #ifdef HAVE_LOGIN_CAP_H
1155 * Don't make it a fatal error if the user didn't specify the login
1156 * class themselves. We do this because if login.conf gets
1157 * corrupted we want the admin to be able to use sudo to fix it.
1160 errflags = NO_MAIL|MSG_ONLY;
1162 errflags = NO_MAIL|MSG_ONLY|NO_EXIT;
1164 if (login_class && strcmp(login_class, "-") != 0) {
1165 if (user_uid != 0 &&
1166 strcmp(runas_user ? runas_user : def_runas_default, "root") != 0)
1167 errorx(1, "only root can use -c %s", login_class);
1169 login_class = pw->pw_class;
1170 if (!login_class || !*login_class)
1172 (pw->pw_uid == 0) ? LOGIN_DEFROOTCLASS : LOGIN_DEFCLASS;
1175 lc = login_getclass(login_class);
1176 if (!lc || !lc->lc_class || strcmp(lc->lc_class, login_class) != 0) {
1177 log_error(errflags, "unknown login class: %s", login_class);
1179 lc = login_getclass(NULL); /* needed for login_getstyle() later */
1188 #endif /* HAVE_LOGIN_CAP_H */
1190 #ifdef HAVE_PROJECT_H
1195 int errflags = NO_MAIL|MSG_ONLY|NO_EXIT;
1197 struct project proj;
1198 struct project *resultp = '\0';
1202 * Collect the default project for the user and settaskid
1205 if (resultp = getdefaultproj(pw->pw_name, &proj, buf, sizeof(buf))) {
1206 errval = setproject(resultp->pj_name, pw->pw_name, TASK_NORMAL);
1209 case SETPROJ_ERR_TASK:
1210 if (errno == EAGAIN)
1211 log_error(errflags, "resource control limit has been reached");
1212 else if (errno == ESRCH)
1213 log_error(errflags, "user \"%s\" is not a member of "
1214 "project \"%s\"", pw->pw_name, resultp->pj_name);
1215 else if (errno == EACCES)
1216 log_error(errflags, "the invoking task is final");
1218 log_error(errflags, "could not join project \"%s\"",
1221 case SETPROJ_ERR_POOL:
1222 if (errno == EACCES)
1223 log_error(errflags, "no resource pool accepting "
1224 "default bindings exists for project \"%s\"",
1226 else if (errno == ESRCH)
1227 log_error(errflags, "specified resource pool does "
1228 "not exist for project \"%s\"", resultp->pj_name);
1230 log_error(errflags, "could not bind to default "
1231 "resource pool for project \"%s\"", resultp->pj_name);
1235 log_error(errflags, "setproject failed for project \"%s\"",
1238 log_error(errflags, "warning, resource control assignment "
1239 "failed for project \"%s\"", resultp->pj_name);
1244 log_error(errflags, "getdefaultproj() error: %s", strerror(errno));
1254 #endif /* HAVE_PROJECT_H */
1257 * Look up the fully qualified domain name and set user_host and user_shost.
1262 #ifdef HAVE_GETADDRINFO
1263 struct addrinfo *res0, hint;
1269 #ifdef HAVE_GETADDRINFO
1270 zero_bytes(&hint, sizeof(hint));
1271 hint.ai_family = PF_UNSPEC;
1272 hint.ai_flags = AI_CANONNAME;
1273 if (getaddrinfo(user_host, NULL, &hint, &res0) != 0) {
1275 if (!(hp = gethostbyname(user_host))) {
1277 log_error(MSG_ONLY|NO_EXIT,
1278 "unable to resolve host %s", user_host);
1280 if (user_shost != user_host)
1283 #ifdef HAVE_GETADDRINFO
1284 user_host = estrdup(res0->ai_canonname);
1287 user_host = estrdup(hp->h_name);
1290 if ((p = strchr(user_host, '.'))) {
1292 user_shost = estrdup(user_host);
1295 user_shost = user_host;
1297 sudo_user.host_fqdn_queried = TRUE;
1301 * Get passwd entry for the user we are going to run commands as.
1302 * By default, this is "root". Updates runas_pw as a side effect.
1309 if ((runas_pw = sudo_getpwuid(atoi(user + 1))) == NULL)
1310 runas_pw = sudo_fakepwnam(user, runas_gr ? runas_gr->gr_gid : 0);
1312 if ((runas_pw = sudo_getpwnam(user)) == NULL)
1313 log_error(NO_MAIL|MSG_ONLY, "unknown user: %s", user);
1318 * Get group entry for the group we are going to run commands as.
1319 * Updates runas_pw as a side effect.
1325 if (*group == '#') {
1326 if ((runas_gr = sudo_getgrgid(atoi(group + 1))) == NULL)
1327 runas_gr = sudo_fakegrnam(group);
1329 if ((runas_gr = sudo_getgrnam(group)) == NULL)
1330 log_error(NO_MAIL|MSG_ONLY, "unknown group: %s", group);
1335 * Get passwd entry for the user we are going to authenticate as.
1336 * By default, this is the user invoking sudo. In the most common
1337 * case, this matches sudo_user.pw or runas_pw.
1339 static struct passwd *
1345 if ((pw = sudo_getpwuid(0)) == NULL)
1346 log_error(0, "unknown uid: 0");
1347 } else if (def_runaspw) {
1348 if ((pw = sudo_getpwnam(def_runas_default)) == NULL)
1349 log_error(0, "unknown user: %s", def_runas_default);
1350 } else if (def_targetpw) {
1351 if (runas_pw->pw_name == NULL)
1352 log_error(NO_MAIL|MSG_ONLY, "unknown uid: %lu",
1353 (unsigned long) runas_pw->pw_uid);
1362 * Cleanup hook for error()/errorx()
1368 struct sudo_nss *nss;
1372 tq_foreach_fwd(snl, nss)
1383 (void) printf("Sudo version %s\n", version);
1384 if (getuid() == 0) {
1386 (void) printf("Sudoers path: %s\n", _PATH_SUDOERS);
1388 # ifdef _PATH_NSSWITCH_CONF
1389 (void) printf("nsswitch path: %s\n", _PATH_NSSWITCH_CONF);
1391 (void) printf("ldap.conf path: %s\n", _PATH_LDAP_CONF);
1392 (void) printf("ldap.secret path: %s\n", _PATH_LDAP_SECRET);
1394 dump_auth_methods();
1402 * Tell which options are mutually exclusive and exit.
1405 usage_excl(exit_val)
1408 warningx("Only one of the -e, -h, -i, -k, -K, -l, -s, -v or -V options may be specified");
1413 * Give usage message and exit.
1414 * The actual usage strings are in sudo_usage.h for configure substitution.
1425 * Use usage vectors appropriate to the progname.
1427 if (strcmp(getprogname(), "sudoedit") == 0) {
1428 uvec[0] = SUDO_USAGE4 + 3;
1431 uvec[0] = SUDO_USAGE1;
1432 uvec[1] = SUDO_USAGE2;
1433 uvec[2] = SUDO_USAGE3;
1434 uvec[3] = SUDO_USAGE4;
1439 * Print usage and wrap lines as needed, depending on the
1442 ulen = (int)strlen(getprogname()) + 8;
1443 lbuf_init(&lbuf, NULL, ulen, 0);
1444 for (i = 0; uvec[i] != NULL; i++) {
1445 lbuf_append(&lbuf, "usage: ", getprogname(), uvec[i], NULL);
1448 lbuf_destroy(&lbuf);