2 * Copyright (c) 1993-1996, 1998-2011 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>
44 #endif /* STDC_HEADERS */
46 # if defined(HAVE_MEMORY_H) && !defined(STDC_HEADERS)
50 #endif /* HAVE_STRING_H */
53 #endif /* HAVE_STRINGS_H */
56 #endif /* HAVE_UNISTD_H */
66 #include <netinet/in.h>
68 #ifdef HAVE_LOGIN_CAP_H
69 # include <login_cap.h>
70 # ifndef LOGIN_DEFROOTCLASS
71 # define LOGIN_DEFROOTCLASS "daemon"
75 # include <selinux/selinux.h>
79 #ifndef HAVE_GETADDRINFO
80 # include "compat/getaddrinfo.h"
84 #include "interfaces.h"
85 #include "sudoers_version.h"
86 #include "auth/sudo_auth.h"
91 static void init_vars(char * const *);
92 static int set_cmnd(void);
93 static void set_loginclass(struct passwd *);
94 static void set_runaspw(const char *);
95 static void set_runasgr(const char *);
96 static int cb_runas_default(const char *);
97 static int sudoers_policy_version(int verbose);
98 static int deserialize_info(char * const settings[], char * const user_info[]);
99 static char *find_editor(int nfiles, char **files, char ***argv_out);
100 static void create_admin_success_flag(void);
105 const char *sudoers_file = _PATH_SUDOERS;
106 mode_t sudoers_mode = SUDOERS_MODE;
107 uid_t sudoers_uid = SUDOERS_UID;
108 gid_t sudoers_gid = SUDOERS_GID;
109 struct sudo_user sudo_user;
110 struct passwd *list_pw;
111 struct interface *interfaces;
114 extern int errorlineno;
115 extern bool parse_error;
116 extern char *errorfile;
117 #ifdef HAVE_BSD_AUTH_H
119 #endif /* HAVE_BSD_AUTH_H */
120 sudo_conv_t sudo_conv;
121 sudo_printf_t sudo_printf;
124 static char *prev_user;
125 static char *runas_user;
126 static char *runas_group;
127 static struct sudo_nss_list *snl;
128 static const char *interfaces_string;
129 static sigaction_t saved_sa_int, saved_sa_quit, saved_sa_tstp;
131 /* XXX - must be extern for audit bits of sudo_auth.c */
135 /* Declared here instead of plugin_error.c for static sudo builds. */
136 sigjmp_buf error_jmp;
139 sudoers_policy_open(unsigned int version, sudo_conv_t conversation,
140 sudo_printf_t plugin_printf, char * const settings[],
141 char * const user_info[], char * const envp[])
143 volatile int sources = 0;
145 struct sudo_nss *nss;
146 debug_decl(sudoers_policy_open, SUDO_DEBUG_PLUGIN)
149 sudo_conv = conversation;
151 sudo_printf = plugin_printf;
153 if (sigsetjmp(error_jmp, 1)) {
154 /* called via error(), errorx() or log_error() */
156 debug_return_bool(-1);
159 bindtextdomain("sudoers", LOCALEDIR);
163 * Ignore keyboard-generated signals so the user cannot interrupt
164 * us at some point and avoid the logging.
165 * Install handler to wait for children when they exit.
167 zero_bytes(&sa, sizeof(sa));
168 sigemptyset(&sa.sa_mask);
169 sa.sa_flags = SA_RESTART;
170 sa.sa_handler = SIG_IGN;
171 (void) sigaction(SIGINT, &sa, &saved_sa_int);
172 (void) sigaction(SIGQUIT, &sa, &saved_sa_quit);
173 (void) sigaction(SIGTSTP, &sa, &saved_sa_tstp);
178 /* Initialize environment functions (including replacements). */
181 /* Setup defaults data structures. */
184 /* Parse settings and user_info */
185 sudo_mode = deserialize_info(settings, user_info);
187 init_vars(envp); /* XXX - move this later? */
189 /* Parse nsswitch.conf for sudoers order. */
190 snl = sudo_read_nss();
192 /* LDAP or NSS may modify the euid so we need to be root for the open. */
193 set_perms(PERM_INITIAL);
194 set_perms(PERM_ROOT);
196 /* Open and parse sudoers, set global defaults */
197 tq_foreach_fwd(snl, nss) {
198 if (nss->open(nss) == 0 && nss->parse(nss) == 0) {
200 if (nss->setdefs(nss) != 0)
201 log_error(NO_STDERR|NO_EXIT, _("problem with defaults entries"));
205 warningx(_("no valid sudoers sources found, quitting"));
206 debug_return_bool(-1);
209 /* XXX - collect post-sudoers parse settings into a function */
212 * Initialize external group plugin, if any.
214 if (def_group_plugin) {
215 if (group_plugin_load(def_group_plugin) != true)
216 def_group_plugin = NULL;
220 * Set runas passwd/group entries based on command line or sudoers.
221 * Note that if runas_group was specified without runas_user we
222 * defer setting runas_pw so the match routines know to ignore it.
224 if (runas_group != NULL) {
225 set_runasgr(runas_group);
226 if (runas_user != NULL)
227 set_runaspw(runas_user);
229 set_runaspw(runas_user ? runas_user : def_runas_default);
231 if (!update_defaults(SETDEF_RUNAS))
232 log_error(NO_STDERR|NO_EXIT, _("problem with defaults entries"));
235 set_fqdn(); /* deferred until after sudoers is parsed */
237 /* Set login class if applicable. */
238 set_loginclass(runas_pw ? runas_pw : sudo_user.pw);
242 debug_return_bool(true);
246 sudoers_policy_close(int exit_status, int error_code)
248 debug_decl(sudoers_policy_close, SUDO_DEBUG_PLUGIN)
250 if (sigsetjmp(error_jmp, 1)) {
251 /* called via error(), errorx() or log_error() */
255 /* We do not currently log the exit status. */
257 warningx(_("unable to execute %s: %s"), safe_cmnd, strerror(error_code));
259 /* Close the session we opened in sudoers_policy_init_session(). */
260 if (ISSET(sudo_mode, MODE_RUN|MODE_EDIT))
261 (void)sudo_auth_end_session(runas_pw);
263 /* Free remaining references to password and group entries. */
264 pw_delref(sudo_user.pw);
266 if (runas_gr != NULL)
268 if (user_group_list != NULL)
269 grlist_delref(user_group_list);
275 * The init_session function is called before executing the command
276 * and before uid/gid changes occur.
279 sudoers_policy_init_session(struct passwd *pwd)
281 debug_decl(sudoers_policy_init, SUDO_DEBUG_PLUGIN)
283 if (sigsetjmp(error_jmp, 1)) {
284 /* called via error(), errorx() or log_error() */
288 debug_return_bool(sudo_auth_begin_session(pwd));
292 sudoers_policy_main(int argc, char * const argv[], int pwflag, char *env_add[],
293 char **command_infop[], char **argv_out[], char **user_env_out[])
295 static char *command_info[32]; /* XXX */
296 char **edit_argv = NULL;
297 struct sudo_nss *nss;
298 int cmnd_status = -1, validated;
299 volatile int info_len = 0;
300 volatile int rval = true;
301 debug_decl(sudoers_policy_main, SUDO_DEBUG_PLUGIN)
303 if (sigsetjmp(error_jmp, 1)) {
304 /* error recovery via error(), errorx() or log_error() */
309 /* Is root even allowed to run sudo? */
310 if (user_uid == 0 && !def_root_sudo) {
311 warningx(_("sudoers specifies that root is not allowed to sudo"));
315 /* Check for -C overriding def_closefrom. */
316 if (user_closefrom >= 0 && user_closefrom != def_closefrom) {
317 if (!def_closefrom_override) {
318 warningx(_("you are not permitted to use the -C option"));
321 def_closefrom = user_closefrom;
324 set_perms(PERM_INITIAL);
326 /* Environment variables specified on the command line. */
327 if (env_add != NULL && env_add[0] != NULL)
328 sudo_user.env_vars = env_add;
331 * Make a local copy of argc/argv, with special handling
332 * for pseudo-commands and the '-i' option.
336 NewArgv = emalloc2(NewArgc + 1, sizeof(char *));
337 NewArgv[0] = user_cmnd;
340 /* Must leave an extra slot before NewArgv for bash's --login */
342 NewArgv = emalloc2(NewArgc + 2, sizeof(char *));
343 memcpy(++NewArgv, argv, argc * sizeof(char *));
344 NewArgv[NewArgc] = NULL;
345 if (ISSET(sudo_mode, MODE_LOGIN_SHELL) && runas_pw != NULL)
346 NewArgv[0] = estrdup(runas_pw->pw_shell);
349 /* If given the -P option, set the "preserve_groups" flag. */
350 if (ISSET(sudo_mode, MODE_PRESERVE_GROUPS))
351 def_preserve_groups = true;
353 /* Find command in path */
354 cmnd_status = set_cmnd();
355 if (cmnd_status == -1) {
360 #ifdef HAVE_SETLOCALE
361 if (!setlocale(LC_ALL, def_sudoers_locale)) {
362 warningx(_("unable to set locale to \"%s\", using \"C\""),
364 setlocale(LC_ALL, "C");
369 * Check sudoers sources.
371 validated = FLAG_NO_USER | FLAG_NO_HOST;
372 tq_foreach_fwd(snl, nss) {
373 validated = nss->lookup(nss, validated, pwflag);
375 if (ISSET(validated, VALIDATE_OK)) {
376 /* Handle "= auth" in netsvc.conf */
377 if (nss->ret_if_found)
380 /* Handle [NOTFOUND=return] */
381 if (nss->ret_if_notfound)
386 if (safe_cmnd == NULL)
387 safe_cmnd = estrdup(user_cmnd);
389 #ifdef HAVE_SETLOCALE
390 setlocale(LC_ALL, "");
393 /* If only a group was specified, set runas_pw based on invoking user. */
394 if (runas_pw == NULL)
395 set_runaspw(user_name);
398 * Look up the timestamp dir owner if one is specified.
400 if (def_timestampowner) {
403 if (*def_timestampowner == '#')
404 pw = sudo_getpwuid(atoi(def_timestampowner + 1));
406 pw = sudo_getpwnam(def_timestampowner);
408 log_error(0, _("timestamp owner (%s): No such user"),
410 timestamp_uid = pw->pw_uid;
414 /* If no command line args and "shell_noargs" is not set, error out. */
415 if (ISSET(sudo_mode, MODE_IMPLIED_SHELL) && !def_shell_noargs) {
416 rval = -2; /* usage error */
420 /* Bail if a tty is required and we don't have one. */
421 if (def_requiretty) {
422 int fd = open(_PATH_TTY, O_RDWR|O_NOCTTY);
424 audit_failure(NewArgv, _("no tty"));
425 warningx(_("sorry, you must have a tty to run sudo"));
432 * We don't reset the environment for sudoedit or if the user
433 * specified the -E command line flag and they have setenv privs.
435 if (ISSET(sudo_mode, MODE_EDIT) ||
436 (ISSET(sudo_mode, MODE_PRESERVE_ENV) && def_setenv))
437 def_env_reset = false;
439 /* Build a new environment that avoids any nasty bits. */
442 /* Require a password if sudoers says so. */
443 rval = check_user(validated, sudo_mode);
447 /* If run as root with SUDO_USER set, set sudo_user.pw to that user. */
448 /* XXX - causes confusion when root is not listed in sudoers */
449 if (sudo_mode & (MODE_RUN | MODE_EDIT) && prev_user != NULL) {
450 if (user_uid == 0 && strcmp(prev_user, "root") != 0) {
453 if ((pw = sudo_getpwnam(prev_user)) != NULL) {
454 if (sudo_user.pw != NULL)
455 pw_delref(sudo_user.pw);
461 /* If the user was not allowed to run the command we are done. */
462 if (!ISSET(validated, VALIDATE_OK)) {
463 if (ISSET(validated, FLAG_NO_USER | FLAG_NO_HOST)) {
464 audit_failure(NewArgv, _("No user or host"));
465 log_denial(validated, 1);
469 * We'd like to not leak path info at all here, but that can
470 * *really* confuse the users. To really close the leak we'd
471 * have to say "not allowed to run foo" even when the problem
472 * is just "no foo in path" since the user can trivially set
473 * their path to just contain a single dir.
475 log_denial(validated,
476 !(cmnd_status == NOT_FOUND_DOT || cmnd_status == NOT_FOUND));
477 if (cmnd_status == NOT_FOUND)
478 warningx(_("%s: command not found"), user_cmnd);
479 else if (cmnd_status == NOT_FOUND_DOT)
480 warningx(_("ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run."), user_cmnd, user_cmnd, user_cmnd);
482 /* Just tell the user they are not allowed to run foo. */
483 log_denial(validated, 1);
485 audit_failure(NewArgv, _("validation failure"));
490 /* Create Ubuntu-style dot file to indicate sudo was successful. */
491 create_admin_success_flag();
493 /* Finally tell the user if the command did not exist. */
494 if (cmnd_status == NOT_FOUND_DOT) {
495 audit_failure(NewArgv, _("command in current directory"));
496 warningx(_("ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run."), user_cmnd, user_cmnd, user_cmnd);
498 } else if (cmnd_status == NOT_FOUND) {
499 audit_failure(NewArgv, _("%s: command not found"), user_cmnd);
500 warningx(_("%s: command not found"), user_cmnd);
504 /* If user specified env vars make sure sudoers allows it. */
505 if (ISSET(sudo_mode, MODE_RUN) && !def_setenv) {
506 if (ISSET(sudo_mode, MODE_PRESERVE_ENV)) {
507 warningx(_("sorry, you are not allowed to preserve the environment"));
510 validate_env_vars(sudo_user.env_vars);
513 if (ISSET(sudo_mode, (MODE_RUN | MODE_EDIT)) && (def_log_input || def_log_output)) {
514 if (def_iolog_file && def_iolog_dir) {
515 command_info[info_len++] = expand_iolog_path("iolog_path=",
516 def_iolog_dir, def_iolog_file, &sudo_user.iolog_file);
517 sudo_user.iolog_file++;
520 command_info[info_len++] = estrdup("iolog_stdin=true");
521 command_info[info_len++] = estrdup("iolog_ttyin=true");
523 if (def_log_output) {
524 command_info[info_len++] = estrdup("iolog_stdout=true");
525 command_info[info_len++] = estrdup("iolog_stderr=true");
526 command_info[info_len++] = estrdup("iolog_ttyout=true");
529 command_info[info_len++] = estrdup("iolog_compress=true");
532 log_allowed(validated);
533 if (ISSET(sudo_mode, MODE_CHECK))
534 rval = display_cmnd(snl, list_pw ? list_pw : sudo_user.pw);
535 else if (ISSET(sudo_mode, MODE_LIST))
536 display_privs(snl, list_pw ? list_pw : sudo_user.pw); /* XXX - return val */
538 /* Cleanup sudoers sources */
539 tq_foreach_fwd(snl, nss) {
542 if (def_group_plugin)
543 group_plugin_unload();
545 if (ISSET(sudo_mode, (MODE_VALIDATE|MODE_CHECK|MODE_LIST))) {
546 /* rval already set appropriately */
551 * Set umask based on sudoers.
552 * If user's umask is more restrictive, OR in those bits too
553 * unless umask_override is set.
555 if (def_umask != 0777) {
556 mode_t mask = def_umask;
557 if (!def_umask_override) {
558 mode_t omask = umask(mask);
562 easprintf(&command_info[info_len++], "umask=0%o", (unsigned int)mask);
565 if (ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
568 /* Convert /bin/sh -> -sh so shell knows it is a login shell */
569 if ((p = strrchr(NewArgv[0], '/')) == NULL)
574 /* Set cwd to run user's homedir. */
575 command_info[info_len++] = fmt_string("cwd", runas_pw->pw_dir);
578 * Newer versions of bash require the --login option to be used
579 * in conjunction with the -c option even if the shell name starts
580 * with a '-'. Unfortunately, bash 1.x uses -login, not --login
581 * so this will cause an error for that.
583 if (NewArgc > 1 && strcmp(NewArgv[0], "-bash") == 0 &&
584 strcmp(NewArgv[1], "-c") == 0) {
585 /* Use the extra slot before NewArgv so we can store --login. */
588 NewArgv[0] = NewArgv[1];
589 NewArgv[1] = "--login";
592 #if defined(__linux__) || defined(_AIX)
593 /* Insert system-wide environment variables. */
594 read_env_file(_PATH_ENVIRONMENT, true);
598 /* Insert system-wide environment variables. */
600 read_env_file(def_env_file, false);
602 /* Insert user-specified environment variables. */
603 insert_env_vars(sudo_user.env_vars);
605 /* Restore signal handlers before we exec. */
606 (void) sigaction(SIGINT, &saved_sa_int, NULL);
607 (void) sigaction(SIGQUIT, &saved_sa_quit, NULL);
608 (void) sigaction(SIGTSTP, &saved_sa_tstp, NULL);
610 if (ISSET(sudo_mode, MODE_EDIT)) {
611 char *editor = find_editor(NewArgc - 1, NewArgv + 1, &edit_argv);
614 command_info[info_len++] = fmt_string("command", editor);
615 command_info[info_len++] = estrdup("sudoedit=true");
617 command_info[info_len++] = fmt_string("command", safe_cmnd);
619 if (def_stay_setuid) {
620 easprintf(&command_info[info_len++], "runas_uid=%u",
621 (unsigned int)user_uid);
622 easprintf(&command_info[info_len++], "runas_gid=%u",
623 (unsigned int)user_gid);
624 easprintf(&command_info[info_len++], "runas_euid=%u",
625 (unsigned int)runas_pw->pw_uid);
626 easprintf(&command_info[info_len++], "runas_egid=%u",
627 runas_gr ? (unsigned int)runas_gr->gr_gid :
628 (unsigned int)runas_pw->pw_gid);
630 easprintf(&command_info[info_len++], "runas_uid=%u",
631 (unsigned int)runas_pw->pw_uid);
632 easprintf(&command_info[info_len++], "runas_gid=%u",
633 runas_gr ? (unsigned int)runas_gr->gr_gid :
634 (unsigned int)runas_pw->pw_gid);
636 if (def_preserve_groups) {
637 command_info[info_len++] = "preserve_groups=true";
643 struct group_list *grlist = get_group_list(runas_pw);
645 /* We reserve an extra spot in the list for the effective gid. */
646 glsize = sizeof("runas_groups=") - 1 +
647 ((grlist->ngids + 1) * (MAX_UID_T_LEN + 1));
648 gid_list = emalloc(glsize);
649 memcpy(gid_list, "runas_groups=", sizeof("runas_groups=") - 1);
650 cp = gid_list + sizeof("runas_groups=") - 1;
652 /* On BSD systems the effective gid is the first group in the list. */
653 egid = runas_gr ? (unsigned int)runas_gr->gr_gid :
654 (unsigned int)runas_pw->pw_gid;
655 len = snprintf(cp, glsize - (cp - gid_list), "%u", egid);
656 if (len < 0 || len >= glsize - (cp - gid_list))
657 errorx(1, _("internal error, runas_groups overflow"));
659 for (i = 0; i < grlist->ngids; i++) {
660 if (grlist->gids[i] != egid) {
661 len = snprintf(cp, glsize - (cp - gid_list), ",%u",
662 (unsigned int) grlist->gids[i]);
663 if (len < 0 || len >= glsize - (cp - gid_list))
664 errorx(1, _("internal error, runas_groups overflow"));
668 command_info[info_len++] = gid_list;
669 grlist_delref(grlist);
671 if (def_closefrom >= 0)
672 easprintf(&command_info[info_len++], "closefrom=%d", def_closefrom);
674 command_info[info_len++] = estrdup("noexec=true");
676 command_info[info_len++] = estrdup("set_utmp=true");
678 command_info[info_len++] = estrdup("use_pty=true");
680 command_info[info_len++] = fmt_string("utmp_user", runas_pw->pw_name);
681 #ifdef HAVE_LOGIN_CAP_H
682 if (def_use_loginclass)
683 command_info[info_len++] = fmt_string("login_class", login_class);
684 #endif /* HAVE_LOGIN_CAP_H */
686 if (user_role != NULL)
687 command_info[info_len++] = fmt_string("selinux_role", user_role);
688 if (user_type != NULL)
689 command_info[info_len++] = fmt_string("selinux_type", user_type);
690 #endif /* HAVE_SELINUX */
692 /* Must audit before uid change. */
693 audit_success(NewArgv);
695 *command_infop = command_info;
697 *argv_out = edit_argv ? edit_argv : NewArgv;
698 *user_env_out = env_get(); /* our private copy */
708 /* Close the password and group files and free up memory. */
712 debug_return_bool(rval);
716 sudoers_policy_check(int argc, char * const argv[], char *env_add[],
717 char **command_infop[], char **argv_out[], char **user_env_out[])
719 debug_decl(sudoers_policy_check, SUDO_DEBUG_PLUGIN)
721 if (!ISSET(sudo_mode, MODE_EDIT))
722 SET(sudo_mode, MODE_RUN);
724 debug_return_bool(sudoers_policy_main(argc, argv, 0, env_add, command_infop,
725 argv_out, user_env_out));
729 sudoers_policy_validate(void)
731 debug_decl(sudoers_policy_validate, SUDO_DEBUG_PLUGIN)
733 user_cmnd = "validate";
734 SET(sudo_mode, MODE_VALIDATE);
736 debug_return_bool(sudoers_policy_main(0, NULL, I_VERIFYPW, NULL, NULL, NULL, NULL));
740 sudoers_policy_invalidate(int remove)
742 debug_decl(sudoers_policy_invalidate, SUDO_DEBUG_PLUGIN)
745 if (sigsetjmp(error_jmp, 1) == 0) {
746 remove_timestamp(remove);
754 sudoers_policy_list(int argc, char * const argv[], int verbose,
755 const char *list_user)
758 debug_decl(sudoers_policy_list, SUDO_DEBUG_PLUGIN)
762 SET(sudo_mode, MODE_CHECK);
764 SET(sudo_mode, MODE_LIST);
768 list_pw = sudo_getpwnam(list_user);
769 if (list_pw == NULL) {
770 warningx(_("unknown user: %s"), list_user);
771 debug_return_bool(-1);
774 rval = sudoers_policy_main(argc, argv, I_LISTPW, NULL, NULL, NULL, NULL);
780 debug_return_bool(rval);
784 * Initialize timezone, set umask, fill in ``sudo_user'' struct and
785 * load the ``interfaces'' array.
788 init_vars(char * const envp[])
791 debug_decl(init_vars, SUDO_DEBUG_PLUGIN)
794 (void) tzset(); /* set the timezone if applicable */
795 #endif /* HAVE_TZSET */
797 for (ep = envp; *ep; ep++) {
798 /* XXX - don't fill in if empty string */
801 if (strncmp("KRB5CCNAME=", *ep, 11) == 0)
802 user_ccname = *ep + 11;
805 if (strncmp("PATH=", *ep, 5) == 0)
809 if (!user_prompt && strncmp("SUDO_PROMPT=", *ep, 12) == 0)
810 user_prompt = *ep + 12;
811 else if (strncmp("SUDO_USER=", *ep, 10) == 0)
812 prev_user = *ep + 10;
818 * Get a local copy of the user's struct passwd with the shadow password
819 * if necessary. It is assumed that euid is 0 at this point so we
820 * can read the shadow passwd file if necessary.
822 if ((sudo_user.pw = sudo_getpwuid(user_uid)) == NULL) {
824 * It is not unusual for users to place "sudo -k" in a .logout
825 * file which can cause sudo to be run during reboot after the
826 * YP/NIS/NIS+/LDAP/etc daemon has died.
828 if (sudo_mode == MODE_KILL || sudo_mode == MODE_INVALIDATE)
829 errorx(1, _("unknown uid: %u"), (unsigned int) user_uid);
831 /* Need to make a fake struct passwd for the call to log_error(). */
832 sudo_user.pw = sudo_fakepwnamid(user_name, user_uid, user_gid);
833 log_error(0, _("unknown uid: %u"), (unsigned int) user_uid);
840 if (user_group_list == NULL)
841 user_group_list = get_group_list(sudo_user.pw);
843 /* Set runas callback. */
844 sudo_defs_table[I_RUNAS_DEFAULT].callback = cb_runas_default;
846 /* It is now safe to use log_error() and set_perms() */
851 * Fill in user_cmnd, user_args, user_base and user_stat variables
852 * and apply any command-specific defaults entries.
858 char *path = user_path;
859 debug_decl(set_cmnd, SUDO_DEBUG_PLUGIN)
861 /* Resolve the path and return. */
863 user_stat = emalloc(sizeof(struct stat));
865 /* Default value for cmnd, overridden below. */
866 if (user_cmnd == NULL)
867 user_cmnd = NewArgv[0];
869 if (sudo_mode & (MODE_RUN | MODE_EDIT | MODE_CHECK)) {
870 if (ISSET(sudo_mode, MODE_RUN | MODE_CHECK)) {
871 if (def_secure_path && !user_is_exempt())
872 path = def_secure_path;
873 set_perms(PERM_RUNAS);
874 rval = find_path(NewArgv[0], &user_cmnd, user_stat, path,
878 /* Failed as root, try as invoking user. */
879 set_perms(PERM_USER);
880 rval = find_path(NewArgv[0], &user_cmnd, user_stat, path,
888 char *to, *from, **av;
891 /* Alloc and build up user_args. */
892 for (size = 0, av = NewArgv + 1; *av; av++)
893 size += strlen(*av) + 1;
894 user_args = emalloc(size);
895 if (ISSET(sudo_mode, MODE_SHELL|MODE_LOGIN_SHELL)) {
897 * When running a command via a shell, the sudo front-end
898 * escapes potential meta chars. We unescape non-spaces
899 * for sudoers matching and logging purposes.
901 for (to = user_args, av = NewArgv + 1; (from = *av); av++) {
903 if (from[0] == '\\' && !isspace((unsigned char)from[1]))
911 for (to = user_args, av = NewArgv + 1; *av; av++) {
912 n = strlcpy(to, *av, size - (to - user_args));
913 if (n >= size - (to - user_args))
914 errorx(1, _("internal error, set_cmnd() overflow"));
922 if (strlen(user_cmnd) >= PATH_MAX)
923 errorx(1, _("%s: %s"), user_cmnd, strerror(ENAMETOOLONG));
925 if ((user_base = strrchr(user_cmnd, '/')) != NULL)
928 user_base = user_cmnd;
930 if (!update_defaults(SETDEF_CMND))
931 log_error(NO_STDERR|NO_EXIT, _("problem with defaults entries"));
933 debug_return_int(rval);
937 * Open sudoers and sanity check mode/owner/type.
938 * Returns a handle to the sudoers file or NULL on error.
941 open_sudoers(const char *sudoers, bool doedit, bool *keepopen)
946 debug_decl(open_sudoers, SUDO_DEBUG_PLUGIN)
949 * Fix the mode and group on sudoers file from old default.
950 * Only works if file system is readable/writable by root.
952 if ((rootstat = stat_sudoers(sudoers, &statbuf)) == 0 &&
953 sudoers_uid == statbuf.st_uid && sudoers_mode != 0400 &&
954 (statbuf.st_mode & 0007777) == 0400) {
956 if (chmod(sudoers, sudoers_mode) == 0) {
957 warningx(_("fixed mode on %s"), sudoers);
958 SET(statbuf.st_mode, sudoers_mode);
959 if (statbuf.st_gid != sudoers_gid) {
960 if (chown(sudoers, (uid_t) -1, sudoers_gid) == 0) {
961 warningx(_("set group on %s"), sudoers);
962 statbuf.st_gid = sudoers_gid;
964 warning(_("unable to set group on %s"), sudoers);
967 warning(_("unable to fix mode on %s"), sudoers);
971 * Sanity checks on sudoers file. Must be done as sudoers
972 * file owner. We already did a stat as root, so use that
973 * data if we can't stat as sudoers file owner.
975 set_perms(PERM_SUDOERS);
977 if (rootstat != 0 && stat_sudoers(sudoers, &statbuf) != 0)
978 log_error(USE_ERRNO|NO_EXIT, _("unable to stat %s"), sudoers);
979 else if (!S_ISREG(statbuf.st_mode))
980 log_error(NO_EXIT, _("%s is not a regular file"), sudoers);
981 else if ((statbuf.st_mode & 07577) != (sudoers_mode & 07577))
982 log_error(NO_EXIT, _("%s is mode 0%o, should be 0%o"), sudoers,
983 (unsigned int) (statbuf.st_mode & 07777),
984 (unsigned int) sudoers_mode);
985 else if (statbuf.st_uid != sudoers_uid)
986 log_error(NO_EXIT, _("%s is owned by uid %u, should be %u"), sudoers,
987 (unsigned int) statbuf.st_uid, (unsigned int) sudoers_uid);
988 else if (statbuf.st_gid != sudoers_gid && ISSET(statbuf.st_mode, S_IRGRP|S_IWGRP))
989 log_error(NO_EXIT, _("%s is owned by gid %u, should be %u"), sudoers,
990 (unsigned int) statbuf.st_gid, (unsigned int) sudoers_gid);
991 else if ((fp = fopen(sudoers, "r")) == NULL)
992 log_error(USE_ERRNO|NO_EXIT, _("unable to open %s"), sudoers);
995 * Make sure we can actually read sudoers so we can present the
996 * user with a reasonable error message (unlike the lexer).
998 if (statbuf.st_size != 0 && fgetc(fp) == EOF) {
999 log_error(USE_ERRNO|NO_EXIT, _("unable to read %s"), sudoers);
1007 (void) fcntl(fileno(fp), F_SETFD, 1);
1010 restore_perms(); /* change back to root */
1011 debug_return_ptr(fp);
1014 #ifdef HAVE_LOGIN_CAP_H
1016 set_loginclass(struct passwd *pw)
1020 debug_decl(set_loginclass, SUDO_DEBUG_PLUGIN)
1022 if (!def_use_loginclass)
1026 * Don't make it a fatal error if the user didn't specify the login
1027 * class themselves. We do this because if login.conf gets
1028 * corrupted we want the admin to be able to use sudo to fix it.
1031 errflags = NO_MAIL|MSG_ONLY;
1033 errflags = NO_MAIL|MSG_ONLY|NO_EXIT;
1035 if (login_class && strcmp(login_class, "-") != 0) {
1036 if (user_uid != 0 &&
1037 strcmp(runas_user ? runas_user : def_runas_default, "root") != 0)
1038 errorx(1, _("only root can use `-c %s'"), login_class);
1040 login_class = pw->pw_class;
1041 if (!login_class || !*login_class)
1043 (pw->pw_uid == 0) ? LOGIN_DEFROOTCLASS : LOGIN_DEFCLASS;
1046 /* Make sure specified login class is valid. */
1047 lc = login_getclass(login_class);
1048 if (!lc || !lc->lc_class || strcmp(lc->lc_class, login_class) != 0) {
1049 log_error(errflags, _("unknown login class: %s"), login_class);
1050 def_use_loginclass = false;
1057 set_loginclass(struct passwd *pw)
1060 #endif /* HAVE_LOGIN_CAP_H */
1063 * Look up the fully qualified domain name and set user_host and user_shost.
1068 struct addrinfo *res0, hint;
1070 debug_decl(set_fqdn, SUDO_DEBUG_PLUGIN)
1072 zero_bytes(&hint, sizeof(hint));
1073 hint.ai_family = PF_UNSPEC;
1074 hint.ai_flags = AI_CANONNAME;
1075 if (getaddrinfo(user_host, NULL, &hint, &res0) != 0) {
1076 log_error(MSG_ONLY|NO_EXIT,
1077 _("unable to resolve host %s"), user_host);
1079 if (user_shost != user_host)
1082 user_host = estrdup(res0->ai_canonname);
1085 if ((p = strchr(user_host, '.')) != NULL)
1086 user_shost = estrndup(user_host, (size_t)(p - user_host));
1088 user_shost = user_host;
1093 * Get passwd entry for the user we are going to run commands as
1094 * and store it in runas_pw. By default, commands run as "root".
1097 set_runaspw(const char *user)
1099 debug_decl(set_runaspw, SUDO_DEBUG_PLUGIN)
1101 if (runas_pw != NULL)
1102 pw_delref(runas_pw);
1104 if ((runas_pw = sudo_getpwuid(atoi(user + 1))) == NULL)
1105 runas_pw = sudo_fakepwnam(user, runas_gr ? runas_gr->gr_gid : 0);
1107 if ((runas_pw = sudo_getpwnam(user)) == NULL)
1108 log_error(NO_MAIL|MSG_ONLY, _("unknown user: %s"), user);
1114 * Get group entry for the group we are going to run commands as
1115 * and store it in runas_gr.
1118 set_runasgr(const char *group)
1120 debug_decl(set_runasgr, SUDO_DEBUG_PLUGIN)
1122 if (runas_gr != NULL)
1123 gr_delref(runas_gr);
1124 if (*group == '#') {
1125 if ((runas_gr = sudo_getgrgid(atoi(group + 1))) == NULL)
1126 runas_gr = sudo_fakegrnam(group);
1128 if ((runas_gr = sudo_getgrnam(group)) == NULL)
1129 log_error(NO_MAIL|MSG_ONLY, _("unknown group: %s"), group);
1135 * Callback for runas_default sudoers setting.
1138 cb_runas_default(const char *user)
1140 /* Only reset runaspw if user didn't specify one. */
1141 if (!runas_user && !runas_group)
1147 * Cleanup hook for error()/errorx()
1150 plugin_cleanup(int gotsignal)
1152 struct sudo_nss *nss;
1155 debug_decl(plugin_cleanup, SUDO_DEBUG_PLUGIN)
1157 tq_foreach_fwd(snl, nss)
1160 if (def_group_plugin)
1161 group_plugin_unload();
1169 sudoers_policy_version(int verbose)
1171 debug_decl(sudoers_policy_version, SUDO_DEBUG_PLUGIN)
1173 if (sigsetjmp(error_jmp, 1)) {
1174 /* error recovery via error(), errorx() or log_error() */
1175 debug_return_bool(-1);
1178 sudo_printf(SUDO_CONV_INFO_MSG, _("Sudoers policy plugin version %s\n"),
1180 sudo_printf(SUDO_CONV_INFO_MSG, _("Sudoers file grammar version %d\n"),
1181 SUDOERS_GRAMMAR_VERSION);
1184 sudo_printf(SUDO_CONV_INFO_MSG, _("\nSudoers path: %s\n"), sudoers_file);
1186 # ifdef _PATH_NSSWITCH_CONF
1187 sudo_printf(SUDO_CONV_INFO_MSG, _("nsswitch path: %s\n"), _PATH_NSSWITCH_CONF);
1189 sudo_printf(SUDO_CONV_INFO_MSG, _("ldap.conf path: %s\n"), _PATH_LDAP_CONF);
1190 sudo_printf(SUDO_CONV_INFO_MSG, _("ldap.secret path: %s\n"), _PATH_LDAP_SECRET);
1192 dump_auth_methods();
1194 sudo_printf(SUDO_CONV_INFO_MSG, "\n");
1195 if (interfaces_string != NULL) {
1196 dump_interfaces(interfaces_string);
1197 sudo_printf(SUDO_CONV_INFO_MSG, "\n");
1200 debug_return_bool(true);
1204 deserialize_info(char * const settings[], char * const user_info[])
1207 const char *p, *groups = NULL;
1208 const char *debug_flags = NULL;
1210 debug_decl(deserialize_info, SUDO_DEBUG_PLUGIN)
1212 #define MATCHES(s, v) (strncmp(s, v, sizeof(v) - 1) == 0)
1214 /* Parse command line settings. */
1215 user_closefrom = -1;
1216 for (cur = settings; *cur != NULL; cur++) {
1217 if (MATCHES(*cur, "closefrom=")) {
1218 user_closefrom = atoi(*cur + sizeof("closefrom=") - 1);
1221 if (MATCHES(*cur, "debug_flags=")) {
1222 debug_flags = *cur + sizeof("debug_flags=") - 1;
1225 if (MATCHES(*cur, "runas_user=")) {
1226 runas_user = *cur + sizeof("runas_user=") - 1;
1229 if (MATCHES(*cur, "runas_group=")) {
1230 runas_group = *cur + sizeof("runas_group=") - 1;
1233 if (MATCHES(*cur, "prompt=")) {
1234 user_prompt = *cur + sizeof("prompt=") - 1;
1235 def_passprompt_override = true;
1238 if (MATCHES(*cur, "set_home=")) {
1239 if (atobool(*cur + sizeof("set_home=") - 1) == true)
1240 SET(flags, MODE_RESET_HOME);
1243 if (MATCHES(*cur, "preserve_environment=")) {
1244 if (atobool(*cur + sizeof("preserve_environment=") - 1) == true)
1245 SET(flags, MODE_PRESERVE_ENV);
1248 if (MATCHES(*cur, "run_shell=")) {
1249 if (atobool(*cur + sizeof("run_shell=") - 1) == true)
1250 SET(flags, MODE_SHELL);
1253 if (MATCHES(*cur, "login_shell=")) {
1254 if (atobool(*cur + sizeof("login_shell=") - 1) == true) {
1255 SET(flags, MODE_LOGIN_SHELL);
1256 def_env_reset = true;
1260 if (MATCHES(*cur, "implied_shell=")) {
1261 if (atobool(*cur + sizeof("implied_shell=") - 1) == true)
1262 SET(flags, MODE_IMPLIED_SHELL);
1265 if (MATCHES(*cur, "preserve_groups=")) {
1266 if (atobool(*cur + sizeof("preserve_groups=") - 1) == true)
1267 SET(flags, MODE_PRESERVE_GROUPS);
1270 if (MATCHES(*cur, "ignore_ticket=")) {
1271 if (atobool(*cur + sizeof("ignore_ticket=") - 1) == true)
1272 SET(flags, MODE_IGNORE_TICKET);
1275 if (MATCHES(*cur, "noninteractive=")) {
1276 if (atobool(*cur + sizeof("noninteractive=") - 1) == true)
1277 SET(flags, MODE_NONINTERACTIVE);
1280 if (MATCHES(*cur, "sudoedit=")) {
1281 if (atobool(*cur + sizeof("sudoedit=") - 1) == true)
1282 SET(flags, MODE_EDIT);
1285 if (MATCHES(*cur, "login_class=")) {
1286 login_class = *cur + sizeof("login_class=") - 1;
1287 def_use_loginclass = true;
1291 if (MATCHES(*cur, "selinux_role=")) {
1292 user_role = *cur + sizeof("selinux_role=") - 1;
1295 if (MATCHES(*cur, "selinux_type=")) {
1296 user_type = *cur + sizeof("selinux_type=") - 1;
1299 #endif /* HAVE_SELINUX */
1300 #ifdef HAVE_BSD_AUTH_H
1301 if (MATCHES(*cur, "bsdauth_type=")) {
1302 login_style = *cur + sizeof("bsdauth_type=") - 1;
1305 #endif /* HAVE_BSD_AUTH_H */
1306 #if !defined(HAVE_GETPROGNAME) && !defined(HAVE___PROGNAME)
1307 if (MATCHES(*cur, "progname=")) {
1308 setprogname(*cur + sizeof("progname=") - 1);
1312 if (MATCHES(*cur, "network_addrs=")) {
1313 interfaces_string = *cur + sizeof("network_addrs=") - 1;
1314 set_interfaces(interfaces_string);
1317 if (MATCHES(*cur, "sudoers_file=")) {
1318 sudoers_file = *cur + sizeof("sudoers_file=") - 1;
1321 if (MATCHES(*cur, "sudoers_uid=")) {
1322 sudoers_uid = (uid_t) atoi(*cur + sizeof("sudoers_uid=") - 1);
1325 if (MATCHES(*cur, "sudoers_gid=")) {
1326 sudoers_gid = (gid_t) atoi(*cur + sizeof("sudoers_gid=") - 1);
1329 if (MATCHES(*cur, "sudoers_mode=")) {
1330 sudoers_mode = (mode_t) strtol(*cur + sizeof("sudoers_mode=") - 1,
1336 for (cur = user_info; *cur != NULL; cur++) {
1337 if (MATCHES(*cur, "user=")) {
1338 user_name = estrdup(*cur + sizeof("user=") - 1);
1341 if (MATCHES(*cur, "uid=")) {
1342 user_uid = (uid_t) atoi(*cur + sizeof("uid=") - 1);
1345 if (MATCHES(*cur, "gid=")) {
1346 p = *cur + sizeof("gid=") - 1;
1347 user_gid = (gid_t) atoi(p);
1350 if (MATCHES(*cur, "groups=")) {
1351 groups = *cur + sizeof("groups=") - 1;
1354 if (MATCHES(*cur, "cwd=")) {
1355 user_cwd = estrdup(*cur + sizeof("cwd=") - 1);
1358 if (MATCHES(*cur, "tty=")) {
1359 user_tty = user_ttypath = estrdup(*cur + sizeof("tty=") - 1);
1360 if (strncmp(user_tty, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
1361 user_tty += sizeof(_PATH_DEV) - 1;
1364 if (MATCHES(*cur, "host=")) {
1365 user_host = user_shost = estrdup(*cur + sizeof("host=") - 1);
1366 if ((p = strchr(user_host, '.')))
1367 user_shost = estrndup(user_host, (size_t)(p - user_host));
1370 if (MATCHES(*cur, "lines=")) {
1371 sudo_user.lines = atoi(*cur + sizeof("lines=") - 1);
1374 if (MATCHES(*cur, "cols=")) {
1375 sudo_user.cols = atoi(*cur + sizeof("cols=") - 1);
1379 if (user_cwd == NULL)
1380 user_cwd = "unknown";
1381 if (user_tty == NULL)
1382 user_tty = "unknown"; /* user_ttypath remains NULL */
1384 if (groups != NULL && groups[0] != '\0') {
1389 /* Count number of groups, including passwd gid. */
1391 for (cp = groups; *cp != '\0'; cp++) {
1396 /* The first gid in the list is the passwd group gid. */
1397 gids = emalloc2(ngids, sizeof(GETGROUPS_T));
1402 gids[ngids] = atoi(cp);
1403 if (gids[0] != gids[ngids])
1405 cp = strchr(cp, ',');
1408 cp++; /* skip over comma */
1410 set_group_list(user_name, gids, ngids);
1414 /* Setup debugging if indicated. */
1415 if (debug_flags != NULL) {
1416 sudo_debug_init(NULL, debug_flags);
1417 for (cur = settings; *cur != NULL; cur++)
1418 sudo_debug_printf(SUDO_DEBUG_INFO, "settings: %s", *cur);
1419 for (cur = user_info; *cur != NULL; cur++)
1420 sudo_debug_printf(SUDO_DEBUG_INFO, "user_info: %s", *cur);
1424 debug_return_int(flags);
1428 resolve_editor(char *editor, int nfiles, char **files, char ***argv_out)
1430 char *cp, **nargv, *editor_path = NULL;
1433 debug_decl(resolve_editor, SUDO_DEBUG_PLUGIN)
1435 editor = estrdup(editor); /* becomes part of argv_out */
1438 * Split editor into an argument vector; editor is reused (do not free).
1439 * The EDITOR and VISUAL environment variables may contain command
1440 * line args so look for those and alloc space for them too.
1443 for (wasblank = false, cp = editor; *cp != '\0'; cp++) {
1444 if (isblank((unsigned char) *cp))
1446 else if (wasblank) {
1451 /* If we can't find the editor in the user's PATH, give up. */
1452 cp = strtok(editor, " \t");
1454 find_path(cp, &editor_path, NULL, getenv("PATH"), 0) != FOUND) {
1456 debug_return_str(NULL);
1458 nargv = (char **) emalloc2(nargc + 1 + nfiles + 1, sizeof(char *));
1459 for (ac = 0; cp != NULL && ac < nargc; ac++) {
1461 cp = strtok(NULL, " \t");
1464 for (i = 0; i < nfiles; )
1465 nargv[ac++] = files[i++];
1469 debug_return_str(editor_path);
1473 * Determine which editor to use. We don't need to worry about restricting
1474 * this to a "safe" editor since it runs with the uid of the invoking user,
1475 * not the runas (privileged) user.
1478 find_editor(int nfiles, char **files, char ***argv_out)
1480 char *cp, *editor, *editor_path = NULL, **ev, *ev0[4];
1481 debug_decl(find_editor, SUDO_DEBUG_PLUGIN)
1484 * If any of SUDO_EDITOR, VISUAL or EDITOR are set, choose the first one.
1486 ev0[0] = "SUDO_EDITOR";
1490 for (ev = ev0; *ev != NULL; ev++) {
1491 if ((editor = getenv(*ev)) != NULL && *editor != '\0') {
1492 editor_path = resolve_editor(editor, nfiles, files, argv_out);
1493 if (editor_path != NULL)
1497 if (editor_path == NULL) {
1498 /* def_editor could be a path, split it up */
1499 editor = estrdup(def_editor);
1500 cp = strtok(editor, ":");
1501 while (cp != NULL && editor_path == NULL) {
1502 editor_path = resolve_editor(cp, nfiles, files, argv_out);
1503 cp = strtok(NULL, ":");
1509 audit_failure(NewArgv, _("%s: command not found"), editor);
1510 warningx(_("%s: command not found"), editor);
1512 debug_return_str(editor_path);
1515 #ifdef USE_ADMIN_FLAG
1517 create_admin_success_flag(void)
1519 struct stat statbuf;
1520 char flagfile[PATH_MAX];
1522 debug_decl(create_admin_success_flag, SUDO_DEBUG_PLUGIN)
1524 /* Check whether the user is in the admin group. */
1525 if (!user_in_group(sudo_user.pw, "admin"))
1528 /* Build path to flag file. */
1529 n = snprintf(flagfile, sizeof(flagfile), "%s/.sudo_as_admin_successful",
1531 if (n <= 0 || n >= sizeof(flagfile))
1534 /* Create admin flag file if it doesn't already exist. */
1535 set_perms(PERM_USER);
1536 if (stat(flagfile, &statbuf) != 0) {
1537 fd = open(flagfile, O_CREAT|O_WRONLY|O_EXCL, 0644);
1543 #else /* !USE_ADMIN_FLAG */
1545 create_admin_success_flag(void)
1549 #endif /* USE_ADMIN_FLAG */
1551 struct policy_plugin sudoers_policy = {
1554 sudoers_policy_open,
1555 sudoers_policy_close,
1556 sudoers_policy_version,
1557 sudoers_policy_check,
1558 sudoers_policy_list,
1559 sudoers_policy_validate,
1560 sudoers_policy_invalidate,
1561 sudoers_policy_init_session