2 * Copyright (c) 1993-1996, 1998-2009 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>
98 #include <sudo_usage.h>
101 #include "interfaces.h"
103 #ifdef USING_NONUNIX_GROUPS
104 # include "nonunix.h"
108 __unused static const char rcsid[] = "$Sudo: sudo.c,v 1.517 2009/05/27 00:49:07 millert Exp $";
114 static void init_vars __P((int, char **));
115 static int set_cmnd __P((int));
116 static int parse_args __P((int, char **));
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 set_runasgr __P((char *));
121 static void set_runaspw __P((char *));
122 static void show_version __P((void));
123 static void usage __P((int))
124 __attribute__((__noreturn__));
125 static void usage_excl __P((int))
126 __attribute__((__noreturn__));
127 static struct passwd *get_authpw __P((void));
128 extern int sudo_edit __P((int, char **, char **));
129 extern void rebuild_env __P((int, int));
130 void validate_env_vars __P((struct list_member *));
131 void insert_env_vars __P((struct list_member *));
137 char **Argv, **NewArgv;
139 static int user_closefrom = -1;
140 struct sudo_user sudo_user;
141 struct passwd *auth_pw, *list_pw;
142 struct interface *interfaces;
147 extern int errorlineno;
148 extern int parse_error;
149 extern char *errorfile;
150 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
151 static struct rlimit corelimit;
152 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
153 #ifdef HAVE_LOGIN_CAP_H
155 #endif /* HAVE_LOGIN_CAP_H */
156 #ifdef HAVE_BSD_AUTH_H
158 #endif /* HAVE_BSD_AUTH_H */
159 sigaction_t saved_sa_int, saved_sa_quit, saved_sa_tstp;
160 static char *runas_user;
161 static char *runas_group;
162 static struct sudo_nss_list *snl;
169 main(argc, argv, envp)
174 int sources = 0, validated;
175 int fd, cmnd_status, sudo_mode, pwflag, rc = 0;
177 struct sudo_nss *nss;
178 #if defined(SUDO_DEVEL) && defined(__OpenBSD__)
179 extern char *malloc_options;
180 malloc_options = "AFGJPR";
183 #ifdef HAVE_SETLOCALE
184 setlocale(LC_ALL, "");
188 if ((Argc = argc) < 1)
191 /* Must be done as the first thing... */
192 #if defined(HAVE_GETPRPWNAM) && defined(HAVE_SET_AUTH_PARAMETERS)
193 (void) set_auth_parameters(Argc, Argv);
194 # ifdef HAVE_INITPRIVS
197 #endif /* HAVE_GETPRPWNAM && HAVE_SET_AUTH_PARAMETERS */
200 errorx(1, "must be setuid root");
204 * Ignore keyboard-generated signals so the user cannot interrupt
205 * us at some point and avoid the logging.
206 * Install handler to wait for children when they exit.
208 zero_bytes(&sa, sizeof(sa));
209 sigemptyset(&sa.sa_mask);
210 sa.sa_flags = SA_RESTART;
211 sa.sa_handler = SIG_IGN;
212 (void) sigaction(SIGINT, &sa, &saved_sa_int);
213 (void) sigaction(SIGQUIT, &sa, &saved_sa_quit);
214 (void) sigaction(SIGTSTP, &sa, &saved_sa_tstp);
217 * Turn off core dumps and make sure fds 0-2 are open.
223 /* Parse our arguments. */
224 sudo_mode = parse_args(Argc, Argv);
226 /* Setup defaults data structures. */
229 /* Load the list of local ip addresses and netmasks. */
233 if (ISSET(sudo_mode, MODE_SHELL))
235 else if (ISSET(sudo_mode, MODE_EDIT))
236 user_cmnd = "sudoedit";
246 case MODE_VALIDATE|MODE_INVALIDATE:
247 user_cmnd = "validate";
251 case MODE_INVALIDATE:
260 case MODE_LIST|MODE_INVALIDATE:
265 case MODE_CHECK|MODE_INVALIDATE:
271 /* Must have a command to run... */
272 if (user_cmnd == NULL && NewArgc == 0)
275 init_vars(sudo_mode, envp); /* XXX - move this later? */
277 #ifdef USING_NONUNIX_GROUPS
278 sudo_nonunix_groupcheck_init(); /* initialise nonunix groups impl */
279 #endif /* USING_NONUNIX_GROUPS */
281 /* Parse nsswitch.conf for sudoers order. */
282 snl = sudo_read_nss();
284 /* Open and parse sudoers, set global defaults */
285 tq_foreach_fwd(snl, nss) {
286 if (nss->open(nss) == 0 && nss->parse(nss) == 0) {
292 log_error(0, "no valid sudoers sources found, quitting");
294 /* XXX - collect post-sudoers parse settings into a function */
297 * Set runas passwd/group entries based on command line or sudoers.
298 * Note that if runas_group was specified without runas_user we
299 * defer setting runas_pw so the match routines know to ignore it.
301 if (runas_group != NULL) {
302 set_runasgr(runas_group);
303 if (runas_user != NULL)
304 set_runaspw(runas_user);
306 set_runaspw(runas_user ? runas_user : def_runas_default);
308 if (!update_defaults(SETDEF_RUNAS))
309 log_error(NO_STDERR|NO_EXIT, "problem with defaults entries");
311 /* Set login class if applicable. */
312 set_loginclass(sudo_user.pw);
314 /* Update initial shell now that runas is set. */
315 if (ISSET(sudo_mode, MODE_LOGIN_SHELL))
316 NewArgv[0] = runas_pw->pw_shell;
318 /* This goes after sudoers is parsed since it may have timestamp options. */
319 if (sudo_mode == MODE_KILL || sudo_mode == MODE_INVALIDATE) {
320 remove_timestamp((sudo_mode == MODE_KILL));
325 /* Is root even allowed to run sudo? */
326 if (user_uid == 0 && !def_root_sudo) {
327 (void) fprintf(stderr,
328 "Sorry, %s has been configured to not allow root to run it.\n",
333 /* Check for -C overriding def_closefrom. */
334 if (user_closefrom >= 0 && user_closefrom != def_closefrom) {
335 if (!def_closefrom_override)
336 errorx(1, "you are not permitted to use the -C option");
338 def_closefrom = user_closefrom;
341 cmnd_status = set_cmnd(sudo_mode);
343 #ifdef HAVE_SETLOCALE
344 if (!setlocale(LC_ALL, def_sudoers_locale)) {
345 warningx("unable to set locale to \"%s\", using \"C\"",
347 setlocale(LC_ALL, "C");
351 validated = FLAG_NO_USER | FLAG_NO_HOST;
352 tq_foreach_fwd(snl, nss) {
353 validated = nss->lookup(nss, validated, pwflag);
355 if (ISSET(validated, VALIDATE_OK)) {
356 /* Handle "= auth" in netsvc.conf */
357 if (nss->ret_if_found)
360 /* Handle [NOTFOUND=return] */
361 if (nss->ret_if_notfound)
366 #ifdef USING_NONUNIX_GROUPS
367 /* Finished with the groupcheck code */
368 sudo_nonunix_groupcheck_cleanup();
371 if (safe_cmnd == NULL)
372 safe_cmnd = estrdup(user_cmnd);
374 #ifdef HAVE_SETLOCALE
375 setlocale(LC_ALL, "");
378 /* If only a group was specified, set runas_pw based on invoking user. */
379 if (runas_pw == NULL)
380 set_runaspw(user_name);
383 * Look up the timestamp dir owner if one is specified.
385 if (def_timestampowner) {
388 if (*def_timestampowner == '#')
389 pw = sudo_getpwuid(atoi(def_timestampowner + 1));
391 pw = sudo_getpwnam(def_timestampowner);
393 log_error(0, "timestamp owner (%s): No such user",
395 timestamp_uid = pw->pw_uid;
398 /* If given the -P option, set the "preserve_groups" flag. */
399 if (ISSET(sudo_mode, MODE_PRESERVE_GROUPS))
400 def_preserve_groups = TRUE;
402 /* If no command line args and "set_home" is not set, error out. */
403 if (ISSET(sudo_mode, MODE_IMPLIED_SHELL) && !def_shell_noargs)
406 /* Bail if a tty is required and we don't have one. */
407 if (def_requiretty) {
408 if ((fd = open(_PATH_TTY, O_RDWR|O_NOCTTY)) == -1) {
409 audit_failure(NewArgv, "no tty");
410 log_error(NO_MAIL, "sorry, you must have a tty to run sudo");
415 /* Use askpass value from sudoers unless user specified their own. */
416 if (def_askpass && !user_askpass)
417 user_askpass = def_askpass;
419 /* User may have overridden environment resetting via the -E flag. */
420 if (ISSET(sudo_mode, MODE_PRESERVE_ENV) && def_setenv)
421 def_env_reset = FALSE;
423 /* Build a new environment that avoids any nasty bits. */
424 rebuild_env(sudo_mode, def_noexec);
426 /* Fill in passwd struct based on user we are authenticating as. */
427 auth_pw = get_authpw();
429 /* Require a password if sudoers says so. */
430 if (def_authenticate)
431 check_user(validated, sudo_mode);
433 /* If run as root with SUDO_USER set, set sudo_user.pw to that user. */
434 /* XXX - causes confusion when root is not listed in sudoers */
435 if (sudo_mode & (MODE_RUN | MODE_EDIT) && prev_user != NULL) {
436 if (user_uid == 0 && strcmp(prev_user, "root") != 0) {
439 if ((pw = sudo_getpwnam(prev_user)) != NULL)
444 if (ISSET(validated, VALIDATE_OK)) {
445 /* Finally tell the user if the command did not exist. */
446 if (cmnd_status == NOT_FOUND_DOT) {
447 audit_failure(NewArgv, "command in current directory");
448 errorx(1, "ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run.", user_cmnd, user_cmnd, user_cmnd);
449 } else if (cmnd_status == NOT_FOUND) {
450 audit_failure(NewArgv, "%s: command not found", user_cmnd);
451 errorx(1, "%s: command not found", user_cmnd);
454 /* If user specified env vars make sure sudoers allows it. */
455 if (ISSET(sudo_mode, MODE_RUN) && !def_setenv) {
456 if (ISSET(sudo_mode, MODE_PRESERVE_ENV))
458 "sorry, you are not allowed to preserve the environment");
460 validate_env_vars(sudo_user.env_vars);
463 log_allowed(validated);
464 if (ISSET(sudo_mode, MODE_CHECK))
465 rc = display_cmnd(snl, list_pw ? list_pw : sudo_user.pw);
466 else if (ISSET(sudo_mode, MODE_LIST))
467 display_privs(snl, list_pw ? list_pw : sudo_user.pw);
469 /* Cleanup sudoers sources */
470 tq_foreach_fwd(snl, nss)
473 /* Deferred exit due to sudo_ldap_close() */
474 if (ISSET(sudo_mode, (MODE_VALIDATE|MODE_CHECK|MODE_LIST)))
478 * Set umask based on sudoers.
479 * If user's umask is more restrictive, OR in those bits too
480 * unless umask_override is set.
482 if (def_umask != 0777) {
483 if (def_umask_override) {
486 mode_t mask = umask(def_umask);
488 if (mask != def_umask)
493 /* Restore coredumpsize resource limit. */
494 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
495 (void) setrlimit(RLIMIT_CORE, &corelimit);
496 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
498 /* Must audit before uid change. */
499 audit_success(NewArgv);
501 /* Become specified user or root if executing a command. */
502 if (ISSET(sudo_mode, MODE_RUN))
503 set_perms(PERM_FULL_RUNAS);
505 if (ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
508 /* Convert /bin/sh -> -sh so shell knows it is a login shell */
509 if ((p = strrchr(NewArgv[0], '/')) == NULL)
514 /* Change to target user's homedir. */
515 if (chdir(runas_pw->pw_dir) == -1)
516 warning("unable to change directory to %s", runas_pw->pw_dir);
518 #if defined(__linux__) || defined(_AIX)
519 /* Insert system-wide environment variables. */
520 read_env_file(_PATH_ENVIRONMENT, TRUE);
524 if (ISSET(sudo_mode, MODE_EDIT))
525 exit(sudo_edit(NewArgc, NewArgv, envp));
527 /* Insert system-wide environment variables. */
529 read_env_file(def_env_file, FALSE);
531 /* Insert user-specified environment variables. */
532 insert_env_vars(sudo_user.env_vars);
534 /* Restore signal handlers before we exec. */
535 (void) sigaction(SIGINT, &saved_sa_int, NULL);
536 (void) sigaction(SIGQUIT, &saved_sa_quit, NULL);
537 (void) sigaction(SIGTSTP, &saved_sa_tstp, NULL);
539 /* Close the password and group files and free up memory. */
543 closefrom(def_closefrom + 1);
546 if (ISSET(sudo_mode, MODE_BACKGROUND) && fork() > 0) {
547 syslog(LOG_AUTH|LOG_ERR, "fork");
551 if (is_selinux_enabled() > 0 && user_role != NULL)
552 selinux_exec(user_role, user_type, NewArgv,
553 ISSET(sudo_mode, MODE_LOGIN_SHELL));
555 execv(safe_cmnd, NewArgv);
559 #endif /* PROFILING */
561 * If we got here then execve() failed...
563 if (errno == ENOEXEC) {
564 NewArgv--; /* at least one extra slot... */
566 NewArgv[1] = safe_cmnd;
567 execv(_PATH_BSHELL, NewArgv);
569 warning("unable to execute %s", safe_cmnd);
571 } else if (ISSET(validated, FLAG_NO_USER | FLAG_NO_HOST)) {
572 audit_failure(NewArgv, "No user or host");
573 log_denial(validated, 1);
578 * We'd like to not leak path info at all here, but that can
579 * *really* confuse the users. To really close the leak we'd
580 * have to say "not allowed to run foo" even when the problem
581 * is just "no foo in path" since the user can trivially set
582 * their path to just contain a single dir.
584 log_denial(validated,
585 !(cmnd_status == NOT_FOUND_DOT || cmnd_status == NOT_FOUND));
586 if (cmnd_status == NOT_FOUND)
587 warningx("%s: command not found", user_cmnd);
588 else if (cmnd_status == NOT_FOUND_DOT)
589 warningx("ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run.", user_cmnd, user_cmnd, user_cmnd);
591 /* Just tell the user they are not allowed to run foo. */
592 log_denial(validated, 1);
594 audit_failure(NewArgv, "validation failure");
597 exit(0); /* not reached */
601 * Initialize timezone, set umask, fill in ``sudo_user'' struct and
602 * load the ``interfaces'' array.
605 init_vars(sudo_mode, envp)
609 char *p, **ep, thost[MAXHOSTNAMELEN + 1];
612 /* Sanity check command from user. */
613 if (user_cmnd == NULL && strlen(NewArgv[0]) >= PATH_MAX)
614 errorx(1, "%s: File name too long", NewArgv[0]);
617 (void) tzset(); /* set the timezone if applicable */
618 #endif /* HAVE_TZSET */
620 /* Default value for cmnd and cwd, overridden later. */
621 if (user_cmnd == NULL)
622 user_cmnd = NewArgv[0];
623 (void) strlcpy(user_cwd, "unknown", sizeof(user_cwd));
626 * We avoid gethostbyname() if possible since we don't want
627 * sudo to block if DNS or NIS is hosed.
628 * "host" is the (possibly fully-qualified) hostname and
629 * "shost" is the unqualified form of the hostname.
631 sudo_user.host_fqdn_queried = FALSE;
632 nohostname = gethostname(thost, sizeof(thost));
634 user_host = user_shost = "localhost";
636 thost[sizeof(thost) - 1] = '\0';
637 user_host = estrdup(thost);
639 /* Defer call to set_fqdn() until log_error() is safe. */
640 user_shost = user_host;
642 user_shost = user_host;
646 if ((p = ttyname(STDIN_FILENO)) || (p = ttyname(STDOUT_FILENO))) {
647 user_tty = user_ttypath = estrdup(p);
648 if (strncmp(user_tty, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
649 user_tty += sizeof(_PATH_DEV) - 1;
651 user_tty = "unknown";
653 for (ep = envp; *ep; ep++) {
654 /* XXX - don't fill in if empty string */
657 if (strncmp("DISPLAY=", *ep, 8) == 0)
658 user_display = *ep + 8;
661 if (strncmp("KRB5CCNAME=", *ep, 11) == 0)
662 user_ccname = *ep + 11;
665 if (strncmp("PATH=", *ep, 5) == 0)
669 if (strncmp("SHELL=", *ep, 6) == 0)
670 user_shell = *ep + 6;
671 else if (!user_prompt && strncmp("SUDO_PROMPT=", *ep, 12) == 0)
672 user_prompt = *ep + 12;
673 else if (strncmp("SUDO_USER=", *ep, 10) == 0)
674 prev_user = *ep + 10;
675 else if (strncmp("SUDO_ASKPASS=", *ep, 13) == 0)
676 user_askpass = *ep + 13;
682 * Get a local copy of the user's struct passwd with the shadow password
683 * if necessary. It is assumed that euid is 0 at this point so we
684 * can read the shadow passwd file if necessary.
686 if ((sudo_user.pw = sudo_getpwuid(getuid())) == NULL) {
687 /* Need to make a fake struct passwd for logging to work. */
689 char pw_name[MAX_UID_T_LEN + 1];
691 pw.pw_uid = getuid();
692 (void) snprintf(pw_name, sizeof(pw_name), "%lu",
693 (unsigned long) pw.pw_uid);
694 pw.pw_name = pw_name;
698 * If we are in -k/-K mode, just spew to stderr. It is not unusual for
699 * users to place "sudo -k" in a .logout file which can cause sudo to
700 * be run during reboot after the YP/NIS/NIS+/LDAP/etc daemon has died.
702 if (sudo_mode == MODE_KILL || sudo_mode == MODE_INVALIDATE)
703 errorx(1, "unknown uid: %s", pw_name);
704 log_error(0, "unknown uid: %s", pw_name);
706 if (user_shell == NULL || *user_shell == '\0')
707 user_shell = estrdup(sudo_user.pw->pw_shell);
709 /* It is now safe to use log_error() and set_perms() */
711 #ifdef HAVE_GETGROUPS
712 if ((user_ngroups = getgroups(0, NULL)) > 0) {
713 user_groups = emalloc2(user_ngroups, sizeof(GETGROUPS_T));
714 if (getgroups(user_ngroups, user_groups) < 0)
715 log_error(USE_ERRNO|MSG_ONLY, "can't get group vector");
721 set_fqdn(); /* may call log_error() */
724 log_error(USE_ERRNO|MSG_ONLY, "can't get hostname");
727 * Get current working directory. Try as user, fall back to root.
729 set_perms(PERM_USER);
730 if (!getcwd(user_cwd, sizeof(user_cwd))) {
731 set_perms(PERM_ROOT);
732 if (!getcwd(user_cwd, sizeof(user_cwd))) {
733 warningx("cannot get working directory");
734 (void) strlcpy(user_cwd, "unknown", sizeof(user_cwd));
737 set_perms(PERM_ROOT);
740 * If we were given the '-e', '-i' or '-s' options we need to redo
741 * NewArgv and NewArgc.
743 if (ISSET(sudo_mode, MODE_EDIT)) {
746 NewArgv[0] = "sudoedit";
747 } else if (ISSET(sudo_mode, MODE_SHELL)) {
750 /* Allocate an extra slot for execve() failure (ENOEXEC). */
751 av = (char **) emalloc2(5, sizeof(char *));
754 av[0] = user_shell; /* may be updated later */
757 char *cmnd, *src, *dst, *end;
758 size = (size_t) (NewArgv[NewArgc - 1] - NewArgv[0]) +
759 strlen(NewArgv[NewArgc - 1]) + 1;
760 cmnd = emalloc(size);
763 for (end = src + size - 1; src < end; src++, dst++)
764 *dst = *src == 0 ? ' ' : *src;
770 av[++NewArgc] = NULL;
776 * Fill in user_cmnd, user_args, user_base and user_stat variables
777 * and apply any command-specific defaults entries.
785 /* Set project if applicable. */
786 set_project(runas_pw);
788 /* Resolve the path and return. */
790 user_stat = emalloc(sizeof(struct stat));
791 if (sudo_mode & (MODE_RUN | MODE_EDIT | MODE_CHECK)) {
792 if (ISSET(sudo_mode, MODE_RUN | MODE_CHECK)) {
793 set_perms(PERM_RUNAS);
794 rval = find_path(NewArgv[0], &user_cmnd, user_stat, user_path);
795 set_perms(PERM_ROOT);
797 /* Failed as root, try as invoking user. */
798 set_perms(PERM_USER);
799 rval = find_path(NewArgv[0], &user_cmnd, user_stat, user_path);
800 set_perms(PERM_ROOT);
809 /* If we didn't realloc NewArgv it is contiguous so just count. */
810 if (!ISSET(sudo_mode, MODE_SHELL)) {
811 size = (size_t) (NewArgv[NewArgc-1] - NewArgv[1]) +
812 strlen(NewArgv[NewArgc-1]) + 1;
814 for (size = 0, from = NewArgv + 1; *from; from++)
815 size += strlen(*from) + 1;
818 /* Alloc and build up user_args. */
819 user_args = (char *) emalloc(size);
820 for (to = user_args, from = NewArgv + 1; *from; from++) {
821 n = strlcpy(to, *from, size - (to - user_args));
822 if (n >= size - (to - user_args))
823 errorx(1, "internal error, init_vars() overflow");
830 if ((user_base = strrchr(user_cmnd, '/')) != NULL)
833 user_base = user_cmnd;
835 if (!update_defaults(SETDEF_CMND))
836 log_error(NO_STDERR|NO_EXIT, "problem with defaults entries");
838 if (!runas_user && !runas_group)
839 set_runaspw(def_runas_default); /* may have been updated above */
845 * Command line argument parsing.
846 * Sets NewArgc and NewArgv which corresponds to the argc/argv we'll use
847 * for the command to be run (if we are running one).
850 parse_args(argc, argv)
854 int mode = 0; /* what mode is sudo to be run in? */
855 int flags = 0; /* mode flags */
858 /* First, check to see if we were invoked as "sudoedit". */
859 if (strcmp(getprogname(), "sudoedit") == 0)
862 /* Returns true if the last option string was "--" */
863 #define got_end_of_args (optind > 1 && argv[optind - 1][0] == '-' && \
864 argv[optind - 1][1] == '-' && argv[optind - 1][2] == '\0')
866 /* Returns true if next option is an environment variable */
867 #define is_envar (optind < argc && argv[optind][0] != '/' && \
868 strchr(argv[optind], '=') != NULL)
870 /* Flags allowed when running a command */
871 valid_flags = MODE_BACKGROUND|MODE_PRESERVE_ENV|MODE_RESET_HOME|
872 MODE_LOGIN_SHELL|MODE_INVALIDATE|MODE_NONINTERACTIVE|
873 MODE_PRESERVE_GROUPS|MODE_SHELL;
876 * We disable arg permutation for GNU getopt().
877 * Some trickiness is required to allow environment variables
878 * to be interspersed with command line options.
880 if ((ch = getopt(argc, argv, "+Aa:bC:c:Eeg:HhiKkLlnPp:r:Sst:U:u:Vv")) != -1) {
883 SET(tgetpass_flags, TGP_ASKPASS);
885 #ifdef HAVE_BSD_AUTH_H
887 login_style = optarg;
891 SET(flags, MODE_BACKGROUND);
894 if ((user_closefrom = atoi(optarg)) < 3) {
895 warningx("the argument to -C must be at least 3");
899 #ifdef HAVE_LOGIN_CAP_H
901 login_class = optarg;
902 def_use_loginclass = TRUE;
906 SET(flags, MODE_PRESERVE_ENV);
909 if (mode && mode != MODE_EDIT)
912 valid_flags = MODE_INVALIDATE|MODE_NONINTERACTIVE;
915 runas_group = optarg;
918 SET(flags, MODE_RESET_HOME);
921 if (mode && mode != MODE_HELP) {
922 if (strcmp(getprogname(), "sudoedit") != 0)
929 SET(flags, MODE_LOGIN_SHELL);
930 def_env_reset = TRUE;
933 SET(flags, MODE_INVALIDATE);
936 if (mode && mode != MODE_KILL)
942 if (mode && mode != MODE_LISTDEFS)
944 mode = MODE_LISTDEFS;
945 valid_flags = MODE_INVALIDATE|MODE_NONINTERACTIVE;
949 if (mode == MODE_LIST)
955 valid_flags = MODE_INVALIDATE|MODE_NONINTERACTIVE;
958 SET(flags, MODE_NONINTERACTIVE);
961 SET(flags, MODE_PRESERVE_GROUPS);
964 user_prompt = optarg;
965 def_passprompt_override = TRUE;
976 SET(tgetpass_flags, TGP_STDIN);
979 SET(flags, MODE_SHELL);
982 if ((list_pw = sudo_getpwnam(optarg)) == NULL)
983 errorx(1, "unknown user: %s", optarg);
989 if (mode && mode != MODE_VALIDATE)
991 mode = MODE_VALIDATE;
992 valid_flags = MODE_INVALIDATE|MODE_NONINTERACTIVE;
995 if (mode && mode != MODE_VERSION)
1003 } else if (!got_end_of_args && is_envar) {
1004 struct list_member *ev;
1006 /* Store environment variable. */
1007 ev = emalloc(sizeof(*ev));
1008 ev->value = argv[optind];
1009 ev->next = sudo_user.env_vars;
1010 sudo_user.env_vars = ev;
1012 /* Crank optind and resume getopt. */
1015 /* Not an option or an environment variable -- we're done. */
1020 NewArgc = argc - optind;
1021 NewArgv = argv + optind;
1024 /* Defer -k mode setting until we know whether it is a flag or not */
1025 if (ISSET(flags, MODE_INVALIDATE) && NewArgc == 0) {
1026 mode = MODE_INVALIDATE; /* -k by itself */
1027 CLR(flags, MODE_INVALIDATE);
1030 mode = MODE_RUN; /* running a command */
1034 if (NewArgc > 0 && mode == MODE_LIST)
1037 if (ISSET(flags, MODE_LOGIN_SHELL)) {
1038 if (ISSET(flags, MODE_SHELL)) {
1039 warningx("you may not specify both the `-i' and `-s' options");
1042 if (ISSET(flags, MODE_PRESERVE_ENV)) {
1043 warningx("you may not specify both the `-i' and `-E' options");
1046 SET(flags, MODE_SHELL);
1048 if ((flags & valid_flags) != flags)
1050 if (mode == MODE_EDIT &&
1051 (ISSET(flags, MODE_PRESERVE_ENV) || sudo_user.env_vars != NULL)) {
1052 if (ISSET(mode, MODE_PRESERVE_ENV))
1053 warningx("the `-E' option is not valid in edit mode");
1054 if (sudo_user.env_vars != NULL)
1055 warningx("you may not specify environment variables in edit mode");
1058 if ((runas_user != NULL || runas_group != NULL) &&
1059 !ISSET(mode, MODE_EDIT | MODE_RUN | MODE_CHECK)) {
1062 if (list_pw != NULL && mode != MODE_LIST && mode != MODE_CHECK) {
1063 warningx("the `-U' option may only be used with the `-l' option");
1066 if (ISSET(tgetpass_flags, TGP_STDIN) && ISSET(tgetpass_flags, TGP_ASKPASS)) {
1067 warningx("the `-A' and `-S' options may not be used together");
1070 if ((NewArgc == 0 && mode == MODE_EDIT) ||
1071 (NewArgc > 0 && !ISSET(mode, MODE_RUN | MODE_EDIT | MODE_CHECK)))
1073 if (NewArgc == 0 && mode == MODE_RUN && !ISSET(flags, MODE_SHELL))
1074 SET(flags, (MODE_IMPLIED_SHELL | MODE_SHELL));
1076 return(mode | flags);
1080 * Open sudoers and sanity check mode/owner/type.
1081 * Returns a handle to the sudoers file or NULL on error.
1084 open_sudoers(sudoers, doedit, keepopen)
1085 const char *sudoers;
1089 struct stat statbuf;
1094 * Fix the mode and group on sudoers file from old default.
1095 * Only works if file system is readable/writable by root.
1097 if ((rootstat = stat_sudoers(sudoers, &statbuf)) == 0 &&
1098 SUDOERS_UID == statbuf.st_uid && SUDOERS_MODE != 0400 &&
1099 (statbuf.st_mode & 0007777) == 0400) {
1101 if (chmod(sudoers, SUDOERS_MODE) == 0) {
1102 warningx("fixed mode on %s", sudoers);
1103 SET(statbuf.st_mode, SUDOERS_MODE);
1104 if (statbuf.st_gid != SUDOERS_GID) {
1105 if (chown(sudoers, (uid_t) -1, SUDOERS_GID) == 0) {
1106 warningx("set group on %s", sudoers);
1107 statbuf.st_gid = SUDOERS_GID;
1109 warning("unable to set group on %s", sudoers);
1112 warning("unable to fix mode on %s", sudoers);
1116 * Sanity checks on sudoers file. Must be done as sudoers
1117 * file owner. We already did a stat as root, so use that
1118 * data if we can't stat as sudoers file owner.
1120 set_perms(PERM_SUDOERS);
1122 if (rootstat != 0 && stat_sudoers(sudoers, &statbuf) != 0)
1123 log_error(USE_ERRNO|NO_EXIT, "can't stat %s", sudoers);
1124 else if (!S_ISREG(statbuf.st_mode))
1125 log_error(NO_EXIT, "%s is not a regular file", sudoers);
1126 else if ((statbuf.st_mode & 07777) != SUDOERS_MODE)
1127 log_error(NO_EXIT, "%s is mode 0%o, should be 0%o", sudoers,
1128 (unsigned int) (statbuf.st_mode & 07777),
1129 (unsigned int) SUDOERS_MODE);
1130 else if (statbuf.st_uid != SUDOERS_UID)
1131 log_error(NO_EXIT, "%s is owned by uid %lu, should be %lu", sudoers,
1132 (unsigned long) statbuf.st_uid, (unsigned long) SUDOERS_UID);
1133 else if (statbuf.st_gid != SUDOERS_GID)
1134 log_error(NO_EXIT, "%s is owned by gid %lu, should be %lu", sudoers,
1135 (unsigned long) statbuf.st_gid, (unsigned long) SUDOERS_GID);
1136 else if ((fp = fopen(sudoers, "r")) == NULL)
1137 log_error(USE_ERRNO, "can't open %s", sudoers);
1140 * Make sure we can actually read sudoers so we can present the
1141 * user with a reasonable error message (unlike the lexer).
1143 if (statbuf.st_size != 0) {
1144 if (fgetc(fp) == EOF)
1145 log_error(USE_ERRNO, "can't read %s", sudoers);
1148 (void) fcntl(fileno(fp), F_SETFD, 1);
1151 set_perms(PERM_ROOT); /* change back to root */
1156 * Close all open files (except std*) and turn off core dumps.
1157 * Also sets the set_perms() pointer to the correct function.
1162 int miss[3], devnull = -1;
1163 #if defined(__linux__) || (defined(RLIMIT_CORE) && !defined(SUDO_DEVEL))
1167 #if defined(__linux__)
1169 * Unlimit the number of processes since Linux's setuid() will
1170 * apply resource limits when changing uid and return EAGAIN if
1171 * nproc would be violated by the uid switch.
1173 rl.rlim_cur = rl.rlim_max = RLIM_INFINITY;
1174 if (setrlimit(RLIMIT_NPROC, &rl)) {
1175 if (getrlimit(RLIMIT_NPROC, &rl) == 0) {
1176 rl.rlim_cur = rl.rlim_max;
1177 (void)setrlimit(RLIMIT_NPROC, &rl);
1180 #endif /* __linux__ */
1181 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
1183 * Turn off core dumps.
1185 (void) getrlimit(RLIMIT_CORE, &corelimit);
1186 memcpy(&rl, &corelimit, sizeof(struct rlimit));
1188 (void) setrlimit(RLIMIT_CORE, &rl);
1189 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
1192 * stdin, stdout and stderr must be open; set them to /dev/null
1193 * if they are closed and close all other fds.
1195 miss[STDIN_FILENO] = fcntl(STDIN_FILENO, F_GETFL, 0) == -1;
1196 miss[STDOUT_FILENO] = fcntl(STDOUT_FILENO, F_GETFL, 0) == -1;
1197 miss[STDERR_FILENO] = fcntl(STDERR_FILENO, F_GETFL, 0) == -1;
1198 if (miss[STDIN_FILENO] || miss[STDOUT_FILENO] || miss[STDERR_FILENO]) {
1199 if ((devnull = open(_PATH_DEVNULL, O_RDWR, 0644)) != -1) {
1200 if (miss[STDIN_FILENO])
1201 (void) dup2(devnull, STDIN_FILENO);
1202 if (miss[STDOUT_FILENO])
1203 (void) dup2(devnull, STDOUT_FILENO);
1204 if (miss[STDERR_FILENO])
1205 (void) dup2(devnull, STDERR_FILENO);
1206 if (devnull > STDERR_FILENO)
1212 #ifdef HAVE_LOGIN_CAP_H
1220 * Don't make it a fatal error if the user didn't specify the login
1221 * class themselves. We do this because if login.conf gets
1222 * corrupted we want the admin to be able to use sudo to fix it.
1225 errflags = NO_MAIL|MSG_ONLY;
1227 errflags = NO_MAIL|MSG_ONLY|NO_EXIT;
1229 if (login_class && strcmp(login_class, "-") != 0) {
1230 if (user_uid != 0 &&
1231 strcmp(runas_user ? runas_user : def_runas_default, "root") != 0)
1232 errorx(1, "only root can use -c %s", login_class);
1234 login_class = pw->pw_class;
1235 if (!login_class || !*login_class)
1237 (pw->pw_uid == 0) ? LOGIN_DEFROOTCLASS : LOGIN_DEFCLASS;
1240 lc = login_getclass(login_class);
1241 if (!lc || !lc->lc_class || strcmp(lc->lc_class, login_class) != 0) {
1242 log_error(errflags, "unknown login class: %s", login_class);
1244 lc = login_getclass(NULL); /* needed for login_getstyle() later */
1253 #endif /* HAVE_LOGIN_CAP_H */
1255 #ifdef HAVE_PROJECT_H
1260 int errflags = NO_MAIL|MSG_ONLY|NO_EXIT;
1262 struct project proj;
1263 struct project *resultp = '\0';
1267 * Collect the default project for the user and settaskid
1270 if (resultp = getdefaultproj(pw->pw_name, &proj, buf, sizeof(buf))) {
1271 errval = setproject(resultp->pj_name, pw->pw_name, TASK_NORMAL);
1274 case SETPROJ_ERR_TASK:
1275 if (errno == EAGAIN)
1276 log_error(errflags, "resource control limit has been reached");
1277 else if (errno == ESRCH)
1278 log_error(errflags, "user \"%s\" is not a member of "
1279 "project \"%s\"", pw->pw_name, resultp->pj_name);
1280 else if (errno == EACCES)
1281 log_error(errflags, "the invoking task is final");
1283 log_error(errflags, "could not join project \"%s\"",
1286 case SETPROJ_ERR_POOL:
1287 if (errno == EACCES)
1288 log_error(errflags, "no resource pool accepting "
1289 "default bindings exists for project \"%s\"",
1291 else if (errno == ESRCH)
1292 log_error(errflags, "specified resource pool does "
1293 "not exist for project \"%s\"", resultp->pj_name);
1295 log_error(errflags, "could not bind to default "
1296 "resource pool for project \"%s\"", resultp->pj_name);
1300 log_error(errflags, "setproject failed for project \"%s\"",
1303 log_error(errflags, "warning, resource control assignment "
1304 "failed for project \"%s\"", resultp->pj_name);
1309 log_error(errflags, "getdefaultproj() error: %s", strerror(errno));
1319 #endif /* HAVE_PROJECT_H */
1322 * Look up the fully qualified domain name and set user_host and user_shost.
1327 #ifdef HAVE_GETADDRINFO
1328 struct addrinfo *res0, hint;
1334 #ifdef HAVE_GETADDRINFO
1335 zero_bytes(&hint, sizeof(hint));
1336 hint.ai_family = PF_UNSPEC;
1337 hint.ai_flags = AI_CANONNAME;
1338 if (getaddrinfo(user_host, NULL, &hint, &res0) != 0) {
1340 if (!(hp = gethostbyname(user_host))) {
1342 log_error(MSG_ONLY|NO_EXIT,
1343 "unable to resolve host %s", user_host);
1345 if (user_shost != user_host)
1348 #ifdef HAVE_GETADDRINFO
1349 user_host = estrdup(res0->ai_canonname);
1352 user_host = estrdup(hp->h_name);
1355 if ((p = strchr(user_host, '.'))) {
1357 user_shost = estrdup(user_host);
1360 user_shost = user_host;
1362 sudo_user.host_fqdn_queried = TRUE;
1366 * Get passwd entry for the user we are going to run commands as.
1367 * By default, this is "root". Updates runas_pw as a side effect.
1374 if ((runas_pw = sudo_getpwuid(atoi(user + 1))) == NULL)
1375 runas_pw = sudo_fakepwnam(user, runas_gr ? runas_gr->gr_gid : 0);
1377 if ((runas_pw = sudo_getpwnam(user)) == NULL) {
1378 audit_failure(NewArgv, "unknown user: %s", user);
1379 log_error(NO_MAIL|MSG_ONLY, "unknown user: %s", user);
1385 * Get group entry for the group we are going to run commands as.
1386 * Updates runas_pw as a side effect.
1392 if (*group == '#') {
1393 if ((runas_gr = sudo_getgrgid(atoi(group + 1))) == NULL)
1394 runas_gr = sudo_fakegrnam(group);
1396 if ((runas_gr = sudo_getgrnam(group)) == NULL)
1397 log_error(NO_MAIL|MSG_ONLY, "unknown group: %s", group);
1402 * Get passwd entry for the user we are going to authenticate as.
1403 * By default, this is the user invoking sudo. In the most common
1404 * case, this matches sudo_user.pw or runas_pw.
1406 static struct passwd *
1412 if ((pw = sudo_getpwuid(0)) == NULL)
1413 log_error(0, "unknown uid: 0");
1414 } else if (def_runaspw) {
1415 if ((pw = sudo_getpwnam(def_runas_default)) == NULL)
1416 log_error(0, "unknown user: %s", def_runas_default);
1417 } else if (def_targetpw) {
1418 if (runas_pw->pw_name == NULL)
1419 log_error(NO_MAIL|MSG_ONLY, "unknown uid: %lu",
1420 (unsigned long) runas_pw->pw_uid);
1429 * Cleanup hook for error()/errorx()
1435 struct sudo_nss *nss;
1439 tq_foreach_fwd(snl, nss)
1450 (void) printf("Sudo version %s\n", PACKAGE_VERSION);
1451 if (getuid() == 0) {
1453 (void) printf("Sudoers path: %s\n", _PATH_SUDOERS);
1455 # ifdef _PATH_NSSWITCH_CONF
1456 (void) printf("nsswitch path: %s\n", _PATH_NSSWITCH_CONF);
1458 (void) printf("ldap.conf path: %s\n", _PATH_LDAP_CONF);
1459 (void) printf("ldap.secret path: %s\n", _PATH_LDAP_SECRET);
1461 dump_auth_methods();
1469 * Tell which options are mutually exclusive and exit.
1472 usage_excl(exit_val)
1475 warningx("Only one of the -e, -h, -i, -K, -l, -s, -v or -V options may be specified");
1480 * Give usage message and exit.
1481 * The actual usage strings are in sudo_usage.h for configure substitution.
1492 * Use usage vectors appropriate to the progname.
1494 if (strcmp(getprogname(), "sudoedit") == 0) {
1495 uvec[0] = SUDO_USAGE5 + 3;
1498 uvec[0] = SUDO_USAGE1;
1499 uvec[1] = SUDO_USAGE2;
1500 uvec[2] = SUDO_USAGE3;
1501 uvec[3] = SUDO_USAGE4;
1502 uvec[4] = SUDO_USAGE5;
1507 * Print usage and wrap lines as needed, depending on the
1510 ulen = (int)strlen(getprogname()) + 8;
1511 lbuf_init(&lbuf, NULL, ulen, 0);
1512 for (i = 0; uvec[i] != NULL; i++) {
1513 lbuf_append(&lbuf, "usage: ", getprogname(), uvec[i], NULL);
1516 lbuf_destroy(&lbuf);