2 * Copyright (c) 1993-1996, 1998-2010 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>
35 #include <sys/param.h>
36 #include <sys/socket.h>
38 # include <sys/time.h>
39 # include <sys/resource.h>
49 #endif /* STDC_HEADERS */
51 # if defined(HAVE_MEMORY_H) && !defined(STDC_HEADERS)
55 #endif /* HAVE_STRING_H */
58 #endif /* HAVE_STRINGS_H */
61 #endif /* HAVE_UNISTD_H */
68 #if TIME_WITH_SYS_TIME
74 #include <netinet/in.h>
76 #if defined(HAVE_GETPRPWNAM) && defined(HAVE_SET_AUTH_PARAMETERS)
79 # include <hpsecurity.h>
81 # include <sys/security.h>
84 #endif /* HAVE_GETPRPWNAM && HAVE_SET_AUTH_PARAMETERS */
85 #ifdef HAVE_LOGIN_CAP_H
86 # include <login_cap.h>
87 # ifndef LOGIN_DEFROOTCLASS
88 # define LOGIN_DEFROOTCLASS "daemon"
91 #ifdef HAVE_MBR_CHECK_MEMBERSHIP
92 # include <membership.h>
97 #include "interfaces.h"
98 #include <sudo_usage.h>
100 #ifdef USING_NONUNIX_GROUPS
101 # include "nonunix.h"
104 #if defined(HAVE_PAM) && !defined(NO_PAM_SESSION)
105 # define CMND_WAIT TRUE
107 # define CMND_WAIT FALSE
113 static void init_vars __P((char **));
114 static int set_cmnd __P((int));
115 static void initial_setup __P((void));
116 static void set_loginclass __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 create_admin_success_flag __P((void));
121 extern int sudo_edit __P((int, char **, char **));
122 int run_command __P((const char *path, char *argv[], char *envp[], uid_t uid, int dowait)); /* XXX should be in sudo.h */
128 char **Argv, **NewArgv;
130 int user_closefrom = -1;
131 struct sudo_user sudo_user;
132 struct passwd *list_pw;
133 struct interface *interfaces;
138 extern int errorlineno;
139 extern int parse_error;
140 extern char *errorfile;
141 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
142 static struct rlimit corelimit;
143 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
144 #if defined(__linux__)
145 static struct rlimit nproclimit;
147 #ifdef HAVE_LOGIN_CAP_H
149 #endif /* HAVE_LOGIN_CAP_H */
150 sigaction_t saved_sa_int, saved_sa_quit, saved_sa_tstp;
153 static struct sudo_nss_list *snl;
161 main(argc, argv, envp)
166 int sources = 0, validated;
167 int fd, cmnd_status, pwflag, rc = 0;
169 struct sudo_nss *nss;
170 #if defined(SUDO_DEVEL) && defined(__OpenBSD__)
171 extern char *malloc_options;
172 malloc_options = "AFGJPR";
175 #ifdef HAVE_SETLOCALE
176 setlocale(LC_ALL, "");
180 if ((Argc = argc) < 1)
183 /* Must be done as the first thing... */
184 #if defined(HAVE_GETPRPWNAM) && defined(HAVE_SET_AUTH_PARAMETERS)
185 (void) set_auth_parameters(Argc, Argv);
186 # ifdef HAVE_INITPRIVS
189 #endif /* HAVE_GETPRPWNAM && HAVE_SET_AUTH_PARAMETERS */
192 errorx(1, "must be setuid root");
196 * Ignore keyboard-generated signals so the user cannot interrupt
197 * us at some point and avoid the logging.
198 * Install handler to wait for children when they exit.
200 zero_bytes(&sa, sizeof(sa));
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);
208 /* Initialize environment functions (including replacements). */
212 * Turn off core dumps and make sure fds 0-2 are open.
218 /* Parse our arguments. */
219 sudo_mode = parse_args(Argc, Argv);
221 /* Setup defaults data structures. */
224 /* Load the list of local ip addresses and netmasks. */
228 if (ISSET(sudo_mode, MODE_SHELL))
230 else if (ISSET(sudo_mode, MODE_EDIT))
231 user_cmnd = "sudoedit";
241 case MODE_VALIDATE|MODE_INVALIDATE:
242 user_cmnd = "validate";
246 case MODE_INVALIDATE:
255 case MODE_LIST|MODE_INVALIDATE:
260 case MODE_CHECK|MODE_INVALIDATE:
266 /* Must have a command to run... */
267 if (user_cmnd == NULL && NewArgc == 0)
270 init_vars(envp); /* XXX - move this later? */
272 #ifdef USING_NONUNIX_GROUPS
273 sudo_nonunix_groupcheck_init(); /* initialise nonunix groups impl */
274 #endif /* USING_NONUNIX_GROUPS */
276 /* Parse nsswitch.conf for sudoers order. */
277 snl = sudo_read_nss();
279 /* Open and parse sudoers, set global defaults */
280 tq_foreach_fwd(snl, nss) {
281 if (nss->open(nss) == 0 && nss->parse(nss) == 0) {
283 if (nss->setdefs(nss) != 0)
284 log_error(NO_STDERR|NO_EXIT, "problem with defaults entries");
288 log_error(0, "no valid sudoers sources found, quitting");
290 /* XXX - collect post-sudoers parse settings into a function */
293 * Set runas passwd/group entries based on command line or sudoers.
294 * Note that if runas_group was specified without runas_user we
295 * defer setting runas_pw so the match routines know to ignore it.
297 if (runas_group != NULL) {
298 set_runasgr(runas_group);
299 if (runas_user != NULL)
300 set_runaspw(runas_user);
302 set_runaspw(runas_user ? runas_user : def_runas_default);
304 if (!update_defaults(SETDEF_RUNAS))
305 log_error(NO_STDERR|NO_EXIT, "problem with defaults entries");
308 set_fqdn(); /* deferred until after sudoers is parsed */
310 /* Set login class if applicable. */
311 set_loginclass(sudo_user.pw);
313 /* Update initial shell now that runas is set. */
314 if (ISSET(sudo_mode, MODE_LOGIN_SHELL))
315 NewArgv[0] = estrdup(runas_pw->pw_shell);
317 /* This goes after sudoers is parsed since it may have timestamp options. */
318 if (sudo_mode == MODE_KILL || sudo_mode == MODE_INVALIDATE) {
319 remove_timestamp((sudo_mode == MODE_KILL));
324 /* Is root even allowed to run sudo? */
325 if (user_uid == 0 && !def_root_sudo) {
326 (void) fprintf(stderr,
327 "Sorry, %s has been configured to not allow root to run it.\n",
332 /* Check for -C overriding def_closefrom. */
333 if (user_closefrom >= 0 && user_closefrom != def_closefrom) {
334 if (!def_closefrom_override)
335 errorx(1, "you are not permitted to use the -C option");
337 def_closefrom = user_closefrom;
340 cmnd_status = set_cmnd(sudo_mode);
342 #ifdef HAVE_SETLOCALE
343 if (!setlocale(LC_ALL, def_sudoers_locale)) {
344 warningx("unable to set locale to \"%s\", using \"C\"",
346 setlocale(LC_ALL, "C");
350 validated = FLAG_NO_USER | FLAG_NO_HOST;
351 tq_foreach_fwd(snl, nss) {
352 validated = nss->lookup(nss, validated, pwflag);
354 if (ISSET(validated, VALIDATE_OK)) {
355 /* Handle "= auth" in netsvc.conf */
356 if (nss->ret_if_found)
359 /* Handle [NOTFOUND=return] */
360 if (nss->ret_if_notfound)
365 if (safe_cmnd == NULL)
366 safe_cmnd = estrdup(user_cmnd);
368 #ifdef HAVE_SETLOCALE
369 setlocale(LC_ALL, "");
372 /* If only a group was specified, set runas_pw based on invoking user. */
373 if (runas_pw == NULL)
374 set_runaspw(user_name);
377 * Look up the timestamp dir owner if one is specified.
379 if (def_timestampowner) {
382 if (*def_timestampowner == '#')
383 pw = sudo_getpwuid(atoi(def_timestampowner + 1));
385 pw = sudo_getpwnam(def_timestampowner);
387 log_error(0, "timestamp owner (%s): No such user",
389 timestamp_uid = pw->pw_uid;
393 /* If given the -P option, set the "preserve_groups" flag. */
394 if (ISSET(sudo_mode, MODE_PRESERVE_GROUPS))
395 def_preserve_groups = TRUE;
397 /* If no command line args and "set_home" is not set, error out. */
398 if (ISSET(sudo_mode, MODE_IMPLIED_SHELL) && !def_shell_noargs)
401 /* Bail if a tty is required and we don't have one. */
402 if (def_requiretty) {
403 if ((fd = open(_PATH_TTY, O_RDWR|O_NOCTTY)) == -1) {
404 audit_failure(NewArgv, "no tty");
405 log_error(NO_MAIL, "sorry, you must have a tty to run sudo");
410 /* Use askpass value from sudoers unless user specified their own. */
411 if (def_askpass && !user_askpass)
412 user_askpass = def_askpass;
415 * We don't reset the environment for sudoedit or if the user
416 * specified the -E command line flag and they have setenv privs.
418 if (ISSET(sudo_mode, MODE_EDIT) ||
419 (ISSET(sudo_mode, MODE_PRESERVE_ENV) && def_setenv))
420 def_env_reset = FALSE;
422 /* Build a new environment that avoids any nasty bits. */
423 rebuild_env(def_noexec);
425 /* Require a password if sudoers says so. */
426 if (def_authenticate)
427 check_user(validated, sudo_mode);
429 /* If run as root with SUDO_USER set, set sudo_user.pw to that user. */
430 /* XXX - causes confusion when root is not listed in sudoers */
431 if (sudo_mode & (MODE_RUN | MODE_EDIT) && prev_user != NULL) {
432 if (user_uid == 0 && strcmp(prev_user, "root") != 0) {
435 if ((pw = sudo_getpwnam(prev_user)) != NULL) {
436 if (sudo_user.pw != NULL)
437 pw_delref(sudo_user.pw);
439 #ifdef HAVE_MBR_CHECK_MEMBERSHIP
440 mbr_uid_to_uuid(user_uid, user_uuid);
446 if (ISSET(validated, VALIDATE_OK)) {
447 /* Create Ubuntu-style dot file to indicate sudo was successful. */
448 create_admin_success_flag();
450 /* Finally tell the user if the command did not exist. */
451 if (cmnd_status == NOT_FOUND_DOT) {
452 audit_failure(NewArgv, "command in current directory");
453 errorx(1, "ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run.", user_cmnd, user_cmnd, user_cmnd);
454 } else if (cmnd_status == NOT_FOUND) {
455 audit_failure(NewArgv, "%s: command not found", user_cmnd);
456 errorx(1, "%s: command not found", user_cmnd);
459 /* If user specified env vars make sure sudoers allows it. */
460 if (ISSET(sudo_mode, MODE_RUN) && !def_setenv) {
461 if (ISSET(sudo_mode, MODE_PRESERVE_ENV))
463 "sorry, you are not allowed to preserve the environment");
465 validate_env_vars(sudo_user.env_vars);
468 #ifdef _PATH_SUDO_IO_LOGDIR
469 /* Get next session ID so we can log it. */
470 if (ISSET(sudo_mode, (MODE_RUN | MODE_EDIT)) && (def_log_input || def_log_output))
473 log_allowed(validated);
474 if (ISSET(sudo_mode, MODE_CHECK))
475 rc = display_cmnd(snl, list_pw ? list_pw : sudo_user.pw);
476 else if (ISSET(sudo_mode, MODE_LIST))
477 display_privs(snl, list_pw ? list_pw : sudo_user.pw);
479 /* Cleanup sudoers sources */
480 tq_foreach_fwd(snl, nss)
483 #ifdef USING_NONUNIX_GROUPS
484 /* Finished with the groupcheck code */
485 sudo_nonunix_groupcheck_cleanup();
488 /* Deferred exit due to sudo_ldap_close() */
489 if (ISSET(sudo_mode, (MODE_VALIDATE|MODE_CHECK|MODE_LIST))) {
495 /* Must audit before uid change. */
496 audit_success(NewArgv);
498 if (ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
501 /* Convert /bin/sh -> -sh so shell knows it is a login shell */
502 if ((p = strrchr(NewArgv[0], '/')) == NULL)
507 #if defined(__linux__) || defined(_AIX)
508 /* Insert system-wide environment variables. */
509 read_env_file(_PATH_ENVIRONMENT, TRUE);
513 if (ISSET(sudo_mode, MODE_RUN)) {
514 /* Insert system-wide environment variables. */
516 read_env_file(def_env_file, FALSE);
518 /* Insert user-specified environment variables. */
519 insert_env_vars(sudo_user.env_vars);
522 /* Restore signal handlers before we exec. */
523 (void) sigaction(SIGINT, &saved_sa_int, NULL);
524 (void) sigaction(SIGQUIT, &saved_sa_quit, NULL);
525 (void) sigaction(SIGTSTP, &saved_sa_tstp, NULL);
527 if (ISSET(sudo_mode, MODE_EDIT)) {
528 exit(sudo_edit(NewArgc, NewArgv, envp));
530 exit(run_command(safe_cmnd, NewArgv, env_get(), runas_pw->pw_uid,
533 } else if (ISSET(validated, FLAG_NO_USER | FLAG_NO_HOST)) {
534 audit_failure(NewArgv, "No user or host");
535 log_denial(validated, 1);
540 * We'd like to not leak path info at all here, but that can
541 * *really* confuse the users. To really close the leak we'd
542 * have to say "not allowed to run foo" even when the problem
543 * is just "no foo in path" since the user can trivially set
544 * their path to just contain a single dir.
546 log_denial(validated,
547 !(cmnd_status == NOT_FOUND_DOT || cmnd_status == NOT_FOUND));
548 if (cmnd_status == NOT_FOUND)
549 warningx("%s: command not found", user_cmnd);
550 else if (cmnd_status == NOT_FOUND_DOT)
551 warningx("ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run.", user_cmnd, user_cmnd, user_cmnd);
553 /* Just tell the user they are not allowed to run foo. */
554 log_denial(validated, 1);
556 audit_failure(NewArgv, "validation failure");
559 exit(0); /* not reached */
563 * Escape any non-alpha numeric or blank characters to make sure
564 * they are not interpreted specially by the shell.
572 /* Worst case scenario, we have to escape everything. */
573 cmnd = dst = emalloc((2 * strlen(src)) + 1);
574 while (*src != '\0') {
575 if (!isalnum((unsigned char)*src) && !isspace((unsigned char)*src) &&
576 *src != '_' && *src != '-') {
577 /* quote potential meta character */
588 * Initialize timezone, set umask, fill in ``sudo_user'' struct and
589 * load the ``interfaces'' array.
595 char *p, **ep, thost[MAXHOSTNAMELEN + 1];
598 /* Sanity check command from user. */
599 if (user_cmnd == NULL && strlen(NewArgv[0]) >= PATH_MAX)
600 errorx(1, "%s: File name too long", NewArgv[0]);
603 (void) tzset(); /* set the timezone if applicable */
604 #endif /* HAVE_TZSET */
606 /* Default value for cmnd and cwd, overridden later. */
607 if (user_cmnd == NULL)
608 user_cmnd = NewArgv[0];
609 (void) strlcpy(user_cwd, "unknown", sizeof(user_cwd));
612 * We avoid gethostbyname() if possible since we don't want
613 * sudo to block if DNS or NIS is hosed.
614 * "host" is the (possibly fully-qualified) hostname and
615 * "shost" is the unqualified form of the hostname.
617 nohostname = gethostname(thost, sizeof(thost));
619 user_host = user_shost = "localhost";
621 thost[sizeof(thost) - 1] = '\0';
622 user_host = estrdup(thost);
623 if ((p = strchr(user_host, '.'))) {
625 user_shost = estrdup(user_host);
628 user_shost = user_host;
632 if ((p = ttyname(STDIN_FILENO)) || (p = ttyname(STDOUT_FILENO)) ||
633 (p = ttyname(STDERR_FILENO))) {
634 user_tty = user_ttypath = estrdup(p);
635 if (strncmp(user_tty, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
636 user_tty += sizeof(_PATH_DEV) - 1;
638 user_tty = "unknown";
640 for (ep = envp; *ep; ep++) {
641 /* XXX - don't fill in if empty string */
644 if (strncmp("DISPLAY=", *ep, 8) == 0)
645 user_display = *ep + 8;
648 if (strncmp("KRB5CCNAME=", *ep, 11) == 0)
649 user_ccname = *ep + 11;
652 if (strncmp("PATH=", *ep, 5) == 0)
656 if (strncmp("SHELL=", *ep, 6) == 0)
657 user_shell = *ep + 6;
658 else if (!user_prompt && strncmp("SUDO_PROMPT=", *ep, 12) == 0)
659 user_prompt = *ep + 12;
660 else if (strncmp("SUDO_USER=", *ep, 10) == 0)
661 prev_user = *ep + 10;
662 else if (strncmp("SUDO_ASKPASS=", *ep, 13) == 0)
663 user_askpass = *ep + 13;
669 * Stash a local copy of the user's struct passwd.
671 if ((sudo_user.pw = sudo_getpwuid(getuid())) == NULL) {
672 /* Need to make a fake struct passwd for logging to work. */
674 char pw_name[MAX_UID_T_LEN + 1];
676 pw.pw_uid = getuid();
677 (void) snprintf(pw_name, sizeof(pw_name), "%u",
678 (unsigned int) pw.pw_uid);
679 pw.pw_name = pw_name;
683 * If we are in -k/-K mode, just spew to stderr. It is not unusual for
684 * users to place "sudo -k" in a .logout file which can cause sudo to
685 * be run during reboot after the YP/NIS/NIS+/LDAP/etc daemon has died.
687 if (sudo_mode == MODE_KILL || sudo_mode == MODE_INVALIDATE)
688 errorx(1, "unknown uid: %s", pw_name);
689 log_error(0, "unknown uid: %s", pw_name);
691 #ifdef HAVE_MBR_CHECK_MEMBERSHIP
692 mbr_uid_to_uuid(user_uid, user_uuid);
694 if (user_shell == NULL || *user_shell == '\0')
695 user_shell = estrdup(sudo_user.pw->pw_shell);
697 /* It is now safe to use log_error() and set_perms() */
699 #ifdef HAVE_GETGROUPS
700 if ((user_ngroups = getgroups(0, NULL)) > 0) {
701 user_groups = emalloc2(user_ngroups, sizeof(GETGROUPS_T));
702 if (getgroups(user_ngroups, user_groups) < 0)
703 log_error(USE_ERRNO|MSG_ONLY, "can't get group vector");
708 log_error(USE_ERRNO|MSG_ONLY, "can't get hostname");
711 * Get current working directory. Try as user, fall back to root.
713 set_perms(PERM_USER);
714 if (!getcwd(user_cwd, sizeof(user_cwd))) {
715 set_perms(PERM_ROOT);
716 if (!getcwd(user_cwd, sizeof(user_cwd))) {
717 warningx("cannot get working directory");
718 (void) strlcpy(user_cwd, "unknown", sizeof(user_cwd));
721 set_perms(PERM_ROOT);
724 * If in shell or edit mode, or if running a pseudo-command
725 * such as "list", we need to redo NewArgv and NewArgc.
727 if (ISSET(sudo_mode, MODE_SHELL)) {
730 /* Allocate an extra slot for execve() failure (ENOEXEC). */
731 av = (char **) emalloc2(5, sizeof(char *));
734 av[0] = user_shell; /* may be updated later */
737 char *cmnd, *src, *dst, *end;
738 cmnd_size = (size_t) (NewArgv[NewArgc - 1] - NewArgv[0]) +
739 strlen(NewArgv[NewArgc - 1]) + 1;
740 cmnd = dst = emalloc(cmnd_size);
742 for (end = src + cmnd_size - 1; src < end; src++, dst++)
743 *dst = *src == '\0' ? ' ' : *src;
749 av[++NewArgc] = NULL;
751 } else if (ISSET(sudo_mode, MODE_EDIT) || NewArgc == 0) {
754 NewArgv[0] = user_cmnd;
759 * Fill in user_cmnd, user_args, user_base and user_stat variables
760 * and apply any command-specific defaults entries.
767 char *path = user_path;
769 /* Resolve the path and return. */
771 user_stat = emalloc(sizeof(struct stat));
772 if (sudo_mode & (MODE_RUN | MODE_EDIT | MODE_CHECK)) {
773 if (ISSET(sudo_mode, MODE_RUN | MODE_CHECK)) {
774 if (def_secure_path && !user_is_exempt())
775 path = def_secure_path;
776 set_perms(PERM_RUNAS);
777 rval = find_path(NewArgv[0], &user_cmnd, user_stat, path,
779 set_perms(PERM_ROOT);
781 /* Failed as root, try as invoking user. */
782 set_perms(PERM_USER);
783 rval = find_path(NewArgv[0], &user_cmnd, user_stat, path,
785 set_perms(PERM_ROOT);
794 /* If we didn't realloc NewArgv it is contiguous so just count. */
795 if (!ISSET(sudo_mode, MODE_SHELL)) {
796 size = (size_t) (NewArgv[NewArgc-1] - NewArgv[1]) +
797 strlen(NewArgv[NewArgc-1]) + 1;
799 for (size = 0, from = NewArgv + 1; *from; from++)
800 size += strlen(*from) + 1;
803 /* Alloc and build up user_args. */
804 user_args = (char *) emalloc(size);
805 for (to = user_args, from = NewArgv + 1; *from; from++) {
806 n = strlcpy(to, *from, size - (to - user_args));
807 if (n >= size - (to - user_args))
808 errorx(1, "internal error, init_vars() overflow");
815 if ((user_base = strrchr(user_cmnd, '/')) != NULL)
818 user_base = user_cmnd;
820 if (!update_defaults(SETDEF_CMND))
821 log_error(NO_STDERR|NO_EXIT, "problem with defaults entries");
823 if (!runas_user && !runas_group)
824 set_runaspw(def_runas_default); /* may have been updated above */
830 * Setup the execution environment immediately prior to the call to execve()
831 * Returns TRUE on success and FALSE on failure.
834 exec_setup(rbac_enabled, ttyname, ttyfd)
843 if (selinux_setup(user_role, user_type, ttyname, ttyfd) == -1)
849 * For sudoedit, the command runas a the user with no additional setup.
851 if (ISSET(sudo_mode, MODE_EDIT)) {
852 set_perms(PERM_FULL_USER);
858 * Set umask based on sudoers.
859 * If user's umask is more restrictive, OR in those bits too
860 * unless umask_override is set.
862 if (def_umask != 0777) {
863 if (def_umask_override) {
866 mode_t mask = umask(def_umask);
868 if (mask != def_umask)
873 /* Restore coredumpsize resource limit. */
874 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
875 (void) setrlimit(RLIMIT_CORE, &corelimit);
876 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
878 if (ISSET(sudo_mode, MODE_RUN))
879 set_perms(PERM_FULL_RUNAS);
881 if (ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
882 /* Change to target user's homedir. */
883 if (chdir(runas_pw->pw_dir) == -1) {
884 warning("unable to change directory to %s", runas_pw->pw_dir);
890 * Restore nproc resource limit if pam_limits didn't do it for us.
891 * We must do this *after* the uid change to avoid potential EAGAIN
894 #if defined(__linux__)
897 if (getrlimit(RLIMIT_NPROC, &rl) == 0) {
898 if (rl.rlim_cur == RLIM_INFINITY && rl.rlim_max == RLIM_INFINITY)
899 (void) setrlimit(RLIMIT_NPROC, &nproclimit);
904 /* Close the password and group files and free up memory. */
907 pw_delref(sudo_user.pw);
909 if (runas_gr != NULL)
919 * Run the command and wait for it to complete.
922 run_command(path, argv, envp, uid, dowait)
929 struct command_status cstat;
936 cstat.type = CMD_INVALID;
939 /* Escape meta chars if running a shell with args. */
940 if (ISSET(sudo_mode, MODE_SHELL) && argv[1] != NULL) {
941 char *cmnd = argv[2];
942 argv[2] = escape_cmnd(cmnd);
946 sudo_execve(path, argv, envp, uid, &cstat, dowait,
947 ISSET(sudo_mode, MODE_BACKGROUND));
949 switch (cstat.type) {
951 /* exec_setup() or execve() returned an error. */
952 warningx("unable to execute %s: %s", path, strerror(cstat.val));
956 /* Command ran, exited or was killed. */
957 if (WIFEXITED(cstat.val))
958 exitcode = WEXITSTATUS(cstat.val);
959 else if (WIFSIGNALED(cstat.val))
960 exitcode = WTERMSIG(cstat.val) | 128;
963 warningx("unexpected child termination condition: %d", cstat.type);
968 #endif /* HAVE_PAM */
969 #ifdef _PATH_SUDO_IO_LOGDIR
974 pw_delref(sudo_user.pw);
976 if (runas_gr != NULL)
982 * Open sudoers and sanity check mode/owner/type.
983 * Returns a handle to the sudoers file or NULL on error.
986 open_sudoers(sudoers, doedit, keepopen)
996 * Fix the mode and group on sudoers file from old default.
997 * Only works if file system is readable/writable by root.
999 if ((rootstat = stat_sudoers(sudoers, &statbuf)) == 0 &&
1000 SUDOERS_UID == statbuf.st_uid && SUDOERS_MODE != 0400 &&
1001 (statbuf.st_mode & 0007777) == 0400) {
1003 if (chmod(sudoers, SUDOERS_MODE) == 0) {
1004 warningx("fixed mode on %s", sudoers);
1005 SET(statbuf.st_mode, SUDOERS_MODE);
1006 if (statbuf.st_gid != SUDOERS_GID) {
1007 if (chown(sudoers, (uid_t) -1, SUDOERS_GID) == 0) {
1008 warningx("set group on %s", sudoers);
1009 statbuf.st_gid = SUDOERS_GID;
1011 warning("unable to set group on %s", sudoers);
1014 warning("unable to fix mode on %s", sudoers);
1018 * Sanity checks on sudoers file. Must be done as sudoers
1019 * file owner. We already did a stat as root, so use that
1020 * data if we can't stat as sudoers file owner.
1022 set_perms(PERM_SUDOERS);
1024 if (rootstat != 0 && stat_sudoers(sudoers, &statbuf) != 0)
1025 log_error(USE_ERRNO|NO_EXIT, "can't stat %s", sudoers);
1026 else if (!S_ISREG(statbuf.st_mode))
1027 log_error(NO_EXIT, "%s is not a regular file", sudoers);
1028 else if ((statbuf.st_mode & 07577) != SUDOERS_MODE)
1029 log_error(NO_EXIT, "%s is mode 0%o, should be 0%o", sudoers,
1030 (unsigned int) (statbuf.st_mode & 07777),
1031 (unsigned int) SUDOERS_MODE);
1032 else if (statbuf.st_uid != SUDOERS_UID)
1033 log_error(NO_EXIT, "%s is owned by uid %u, should be %u", sudoers,
1034 (unsigned int) statbuf.st_uid, (unsigned int) SUDOERS_UID);
1035 else if (statbuf.st_gid != SUDOERS_GID)
1036 log_error(NO_EXIT, "%s is owned by gid %u, should be %u", sudoers,
1037 (unsigned int) statbuf.st_gid, (unsigned int) SUDOERS_GID);
1038 else if ((fp = fopen(sudoers, "r")) == NULL)
1039 log_error(USE_ERRNO|NO_EXIT, "can't open %s", sudoers);
1042 * Make sure we can actually read sudoers so we can present the
1043 * user with a reasonable error message (unlike the lexer).
1045 if (statbuf.st_size != 0 && fgetc(fp) == EOF) {
1046 log_error(USE_ERRNO|NO_EXIT, "can't read %s", sudoers);
1054 (void) fcntl(fileno(fp), F_SETFD, 1);
1057 set_perms(PERM_ROOT); /* change back to root */
1062 * Close all open files (except std*) and turn off core dumps.
1063 * Also sets the set_perms() pointer to the correct function.
1068 int miss[3], devnull = -1;
1070 #if defined(__linux__) || (defined(RLIMIT_CORE) && !defined(SUDO_DEVEL))
1074 /* Reset signal mask. */
1075 (void) sigemptyset(&mask);
1076 (void) sigprocmask(SIG_SETMASK, &mask, NULL);
1078 #if defined(__linux__)
1080 * Unlimit the number of processes since Linux's setuid() will
1081 * apply resource limits when changing uid and return EAGAIN if
1082 * nproc would be violated by the uid switch.
1084 (void) getrlimit(RLIMIT_NPROC, &nproclimit);
1085 rl.rlim_cur = rl.rlim_max = RLIM_INFINITY;
1086 if (setrlimit(RLIMIT_NPROC, &rl)) {
1087 memcpy(&rl, &nproclimit, sizeof(struct rlimit));
1088 rl.rlim_cur = rl.rlim_max;
1089 (void)setrlimit(RLIMIT_NPROC, &rl);
1091 #endif /* __linux__ */
1092 #if defined(RLIMIT_CORE) && !defined(SUDO_DEVEL)
1094 * Turn off core dumps.
1096 (void) getrlimit(RLIMIT_CORE, &corelimit);
1097 memcpy(&rl, &corelimit, sizeof(struct rlimit));
1099 (void) setrlimit(RLIMIT_CORE, &rl);
1100 #endif /* RLIMIT_CORE && !SUDO_DEVEL */
1103 * stdin, stdout and stderr must be open; set them to /dev/null
1104 * if they are closed and close all other fds.
1106 miss[STDIN_FILENO] = fcntl(STDIN_FILENO, F_GETFL, 0) == -1;
1107 miss[STDOUT_FILENO] = fcntl(STDOUT_FILENO, F_GETFL, 0) == -1;
1108 miss[STDERR_FILENO] = fcntl(STDERR_FILENO, F_GETFL, 0) == -1;
1109 if (miss[STDIN_FILENO] || miss[STDOUT_FILENO] || miss[STDERR_FILENO]) {
1110 if ((devnull = open(_PATH_DEVNULL, O_RDWR, 0644)) == -1)
1111 error(1, "unable to open %s", _PATH_DEVNULL);
1112 if (miss[STDIN_FILENO] && dup2(devnull, STDIN_FILENO) == -1)
1114 if (miss[STDOUT_FILENO] && dup2(devnull, STDOUT_FILENO) == -1)
1116 if (miss[STDERR_FILENO] && dup2(devnull, STDERR_FILENO) == -1)
1118 if (devnull > STDERR_FILENO)
1123 #ifdef HAVE_LOGIN_CAP_H
1131 * Don't make it a fatal error if the user didn't specify the login
1132 * class themselves. We do this because if login.conf gets
1133 * corrupted we want the admin to be able to use sudo to fix it.
1136 errflags = NO_MAIL|MSG_ONLY;
1138 errflags = NO_MAIL|MSG_ONLY|NO_EXIT;
1140 if (login_class && strcmp(login_class, "-") != 0) {
1141 if (user_uid != 0 &&
1142 strcmp(runas_user ? runas_user : def_runas_default, "root") != 0)
1143 errorx(1, "only root can use -c %s", login_class);
1145 login_class = pw->pw_class;
1146 if (!login_class || !*login_class)
1148 (pw->pw_uid == 0) ? LOGIN_DEFROOTCLASS : LOGIN_DEFCLASS;
1151 lc = login_getclass(login_class);
1152 if (!lc || !lc->lc_class || strcmp(lc->lc_class, login_class) != 0) {
1153 log_error(errflags, "unknown login class: %s", login_class);
1155 lc = login_getclass(NULL); /* needed for login_getstyle() later */
1164 #endif /* HAVE_LOGIN_CAP_H */
1167 * Look up the fully qualified domain name and set user_host and user_shost.
1172 #ifdef HAVE_GETADDRINFO
1173 struct addrinfo *res0, hint;
1179 #ifdef HAVE_GETADDRINFO
1180 zero_bytes(&hint, sizeof(hint));
1181 hint.ai_family = PF_UNSPEC;
1182 hint.ai_flags = AI_CANONNAME;
1183 if (getaddrinfo(user_host, NULL, &hint, &res0) != 0) {
1185 if (!(hp = gethostbyname(user_host))) {
1187 log_error(MSG_ONLY|NO_EXIT,
1188 "unable to resolve host %s", user_host);
1190 if (user_shost != user_host)
1193 #ifdef HAVE_GETADDRINFO
1194 user_host = estrdup(res0->ai_canonname);
1197 user_host = estrdup(hp->h_name);
1200 if ((p = strchr(user_host, '.'))) {
1202 user_shost = estrdup(user_host);
1205 user_shost = user_host;
1210 * Get passwd entry for the user we are going to run commands as
1211 * and store it in runas_pw. By default, commands run as "root".
1217 if (runas_pw != NULL)
1218 pw_delref(runas_pw);
1220 if ((runas_pw = sudo_getpwuid(atoi(user + 1))) == NULL)
1221 runas_pw = sudo_fakepwnam(user, runas_gr ? runas_gr->gr_gid : 0);
1223 if ((runas_pw = sudo_getpwnam(user)) == NULL) {
1224 audit_failure(NewArgv, "unknown user: %s", user);
1225 log_error(NO_MAIL|MSG_ONLY, "unknown user: %s", user);
1231 * Get group entry for the group we are going to run commands as
1232 * and store it in runas_gr.
1238 if (runas_gr != NULL)
1239 gr_delref(runas_gr);
1240 if (*group == '#') {
1241 if ((runas_gr = sudo_getgrgid(atoi(group + 1))) == NULL)
1242 runas_gr = sudo_fakegrnam(group);
1244 if ((runas_gr = sudo_getgrnam(group)) == NULL)
1245 log_error(NO_MAIL|MSG_ONLY, "unknown group: %s", group);
1250 * Cleanup hook for error()/errorx()
1256 struct sudo_nss *nss;
1260 tq_foreach_fwd(snl, nss)
1263 #ifdef USING_NONUNIX_GROUPS
1264 sudo_nonunix_groupcheck_cleanup();
1268 #ifdef _PATH_SUDO_IO_LOGDIR
1272 term_restore(STDIN_FILENO, 0);
1274 selinux_restore_tty();
1281 (void) printf("Sudo version %s\n", PACKAGE_VERSION);
1282 if (getuid() == 0) {
1284 (void) printf("Configure args: %s\n", CONFIGURE_ARGS);
1285 (void) printf("Sudoers path: %s\n", _PATH_SUDOERS);
1287 # ifdef _PATH_NSSWITCH_CONF
1288 (void) printf("nsswitch path: %s\n", _PATH_NSSWITCH_CONF);
1290 (void) printf("ldap.conf path: %s\n", _PATH_LDAP_CONF);
1291 (void) printf("ldap.secret path: %s\n", _PATH_LDAP_SECRET);
1293 dump_auth_methods();
1300 #ifdef USE_ADMIN_FLAG
1302 create_admin_success_flag()
1304 struct stat statbuf;
1305 char flagfile[PATH_MAX];
1308 /* Check whether the user is in the admin group. */
1309 if (!user_in_group(sudo_user.pw, "admin"))
1312 /* Build path to flag file. */
1313 n = snprintf(flagfile, sizeof(flagfile), "%s/.sudo_as_admin_successful",
1315 if (n <= 0 || n >= sizeof(flagfile))
1318 /* Create admin flag file if it doesn't already exist. */
1319 set_perms(PERM_USER);
1320 if (stat(flagfile, &statbuf) == 0) {
1321 set_perms(PERM_ROOT);
1325 fd = open(flagfile, O_CREAT|O_WRONLY|O_EXCL, 0644);
1327 set_perms(PERM_ROOT);
1329 #else /* !USE_ADMIN_FLAG */
1331 create_admin_success_flag()
1335 #endif /* USE_ADMIN_FLAG */