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>
77 #ifdef HAVE_MBR_CHECK_MEMBERSHIP
78 # include <membership.h>
85 #include "interfaces.h"
86 #include "sudoers_version.h"
87 #include "auth/sudo_auth.h"
92 static void init_vars(char * const *);
93 static int set_cmnd(int);
94 static void set_loginclass(struct passwd *);
95 static void set_runasgr(char *);
96 static void set_runaspw(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);
103 extern int runas_ngroups;
104 extern GETGROUPS_T *runas_groups;
109 const char *sudoers_file = _PATH_SUDOERS;
110 mode_t sudoers_mode = SUDOERS_MODE;
111 uid_t sudoers_uid = SUDOERS_UID;
112 gid_t sudoers_gid = SUDOERS_GID;
113 struct sudo_user sudo_user;
114 struct passwd *list_pw;
115 struct interface *interfaces;
119 extern int errorlineno;
120 extern int parse_error;
121 extern char *errorfile;
122 #ifdef HAVE_LOGIN_CAP_H
124 #endif /* HAVE_LOGIN_CAP_H */
125 #ifdef HAVE_BSD_AUTH_H
127 #endif /* HAVE_BSD_AUTH_H */
128 sudo_conv_t sudo_conv;
129 sudo_printf_t sudo_printf;
132 static char *prev_user;
133 static char *runas_user;
134 static char *runas_group;
135 static struct sudo_nss_list *snl;
136 static const char *interfaces_string;
137 static sigaction_t saved_sa_int, saved_sa_quit, saved_sa_tstp;
139 /* XXX - must be extern for audit bits of sudo_auth.c */
144 extern sigjmp_buf error_jmp;
147 sudoers_policy_open(unsigned int version, sudo_conv_t conversation,
148 sudo_printf_t plugin_printf, char * const settings[],
149 char * const user_info[], char * const envp[])
151 volatile int sources = 0;
153 struct sudo_nss *nss;
156 sudo_conv = conversation;
158 sudo_printf = plugin_printf;
160 if (sigsetjmp(error_jmp, 1)) {
161 /* called via error(), errorx() or log_error() */
168 * Ignore keyboard-generated signals so the user cannot interrupt
169 * us at some point and avoid the logging.
170 * Install handler to wait for children when they exit.
172 zero_bytes(&sa, sizeof(sa));
173 sigemptyset(&sa.sa_mask);
174 sa.sa_flags = SA_RESTART;
175 sa.sa_handler = SIG_IGN;
176 (void) sigaction(SIGINT, &sa, &saved_sa_int);
177 (void) sigaction(SIGQUIT, &sa, &saved_sa_quit);
178 (void) sigaction(SIGTSTP, &sa, &saved_sa_tstp);
183 /* Initialize environment functions (including replacements). */
186 /* Setup defaults data structures. */
189 /* Parse settings and user_info */
190 sudo_mode = deserialize_info(settings, user_info);
192 init_vars(envp); /* XXX - move this later? */
194 /* Parse nsswitch.conf for sudoers order. */
195 snl = sudo_read_nss();
197 set_perms(PERM_INITIAL);
199 /* Open and parse sudoers, set global defaults */
200 tq_foreach_fwd(snl, nss) {
201 if (nss->open(nss) == 0 && nss->parse(nss) == 0) {
203 if (nss->setdefs(nss) != 0)
204 log_error(NO_STDERR|NO_EXIT, "problem with defaults entries");
208 warningx("no valid sudoers sources found, quitting");
212 /* XXX - collect post-sudoers parse settings into a function */
215 * Initialize external group plugin.
217 if (def_group_plugin) {
218 switch (group_plugin_load(def_group_plugin)) {
222 def_group_plugin = NULL;
227 * Set runas passwd/group entries based on command line or sudoers.
228 * Note that if runas_group was specified without runas_user we
229 * defer setting runas_pw so the match routines know to ignore it.
231 if (runas_group != NULL) {
232 set_runasgr(runas_group);
233 if (runas_user != NULL)
234 set_runaspw(runas_user);
236 set_runaspw(runas_user ? runas_user : def_runas_default);
238 if (!update_defaults(SETDEF_RUNAS))
239 log_error(NO_STDERR|NO_EXIT, "problem with defaults entries");
242 set_fqdn(); /* deferred until after sudoers is parsed */
244 /* Set login class if applicable. */
245 set_loginclass(sudo_user.pw);
253 sudoers_policy_close(int exit_status, int error_code)
255 if (sigsetjmp(error_jmp, 1)) {
256 /* called via error(), errorx() or log_error() */
260 /* We do not currently log the exit status. */
262 warningx("unable to execute %s: %s", safe_cmnd, strerror(error_code));
264 /* Close the session we opened in sudoers_policy_init_session(). */
265 if (ISSET(sudo_mode, MODE_RUN|MODE_EDIT))
266 (void)auth_end_session();
268 /* Free remaining references to password and group entries. */
269 pw_delref(sudo_user.pw);
271 if (runas_gr != NULL)
276 * The init_session function is called before executing the command
277 * and before uid/gid changes occur.
280 sudoers_policy_init_session(struct passwd *pwd)
282 if (sigsetjmp(error_jmp, 1)) {
283 /* called via error(), errorx() or log_error() */
287 return auth_begin_session(pwd);
291 sudoers_policy_main(int argc, char * const argv[], int pwflag, char *env_add[],
292 char **command_infop[], char **argv_out[], char **user_env_out[])
294 static char *command_info[32]; /* XXX */
295 char **edit_argv = NULL;
296 struct sudo_nss *nss;
297 int cmnd_status = -1, validated;
298 volatile int info_len = 0;
299 volatile int rval = TRUE;
301 if (sigsetjmp(error_jmp, 1)) {
302 /* error recovery via error(), errorx() or log_error() */
307 /* Is root even allowed to run sudo? */
308 if (user_uid == 0 && !def_root_sudo) {
309 warningx("sudoers specifies that root is not allowed to sudo");
313 /* Check for -C overriding def_closefrom. */
314 if (user_closefrom >= 0 && user_closefrom != def_closefrom) {
315 if (!def_closefrom_override) {
316 warningx("you are not permitted to use the -C option");
319 def_closefrom = user_closefrom;
322 set_perms(PERM_INITIAL);
324 /* Environment variables specified on the command line. */
325 if (env_add != NULL && env_add[0] != NULL)
326 sudo_user.env_vars = env_add;
329 * Make a local copy of argc/argv, with special handling
330 * for pseudo-commands and the '-i' option.
334 NewArgv = emalloc2(NewArgc + 1, sizeof(char *));
335 NewArgv[0] = user_cmnd;
339 NewArgv = emalloc2(NewArgc + 1, sizeof(char *));
340 memcpy(NewArgv, argv, argc * sizeof(char *));
341 NewArgv[NewArgc] = NULL;
342 if (ISSET(sudo_mode, MODE_LOGIN_SHELL))
343 NewArgv[0] = estrdup(runas_pw->pw_shell);
346 /* Find command in path */
347 cmnd_status = set_cmnd(sudo_mode);
348 if (cmnd_status == -1) {
353 #ifdef HAVE_SETLOCALE
354 if (!setlocale(LC_ALL, def_sudoers_locale)) {
355 warningx("unable to set locale to \"%s\", using \"C\"",
357 setlocale(LC_ALL, "C");
362 * Check sudoers sources.
364 validated = FLAG_NO_USER | FLAG_NO_HOST;
365 tq_foreach_fwd(snl, nss) {
366 validated = nss->lookup(nss, validated, pwflag);
368 if (ISSET(validated, VALIDATE_OK)) {
369 /* Handle "= auth" in netsvc.conf */
370 if (nss->ret_if_found)
373 /* Handle [NOTFOUND=return] */
374 if (nss->ret_if_notfound)
379 if (safe_cmnd == NULL)
380 safe_cmnd = estrdup(user_cmnd);
382 #ifdef HAVE_SETLOCALE
383 setlocale(LC_ALL, "");
386 /* If only a group was specified, set runas_pw based on invoking user. */
387 if (runas_pw == NULL)
388 set_runaspw(user_name);
391 * Look up the timestamp dir owner if one is specified.
393 if (def_timestampowner) {
396 if (*def_timestampowner == '#')
397 pw = sudo_getpwuid(atoi(def_timestampowner + 1));
399 pw = sudo_getpwnam(def_timestampowner);
401 log_error(0, "timestamp owner (%s): No such user",
403 timestamp_uid = pw->pw_uid;
407 /* If given the -P option, set the "preserve_groups" flag. */
408 if (ISSET(sudo_mode, MODE_PRESERVE_GROUPS))
409 def_preserve_groups = TRUE;
411 /* If no command line args and "shell_noargs" is not set, error out. */
412 if (ISSET(sudo_mode, MODE_IMPLIED_SHELL) && !def_shell_noargs) {
413 rval = -2; /* usage error */
417 /* Bail if a tty is required and we don't have one. */
418 if (def_requiretty) {
419 int fd = open(_PATH_TTY, O_RDWR|O_NOCTTY);
421 audit_failure(NewArgv, "no tty");
422 warningx("sorry, you must have a tty to run sudo");
429 * We don't reset the environment for sudoedit or if the user
430 * specified the -E command line flag and they have setenv privs.
432 if (ISSET(sudo_mode, MODE_EDIT) ||
433 (ISSET(sudo_mode, MODE_PRESERVE_ENV) && def_setenv))
434 def_env_reset = FALSE;
436 /* Build a new environment that avoids any nasty bits. */
439 /* Require a password if sudoers says so. */
440 if (def_authenticate) {
441 int rc = check_user(validated, sudo_mode);
448 /* If run as root with SUDO_USER set, set sudo_user.pw to that user. */
449 /* XXX - causes confusion when root is not listed in sudoers */
450 if (sudo_mode & (MODE_RUN | MODE_EDIT) && prev_user != NULL) {
451 if (user_uid == 0 && strcmp(prev_user, "root") != 0) {
454 if ((pw = sudo_getpwnam(prev_user)) != NULL) {
455 if (sudo_user.pw != NULL)
456 pw_delref(sudo_user.pw);
458 #ifdef HAVE_MBR_CHECK_MEMBERSHIP
459 mbr_uid_to_uuid(user_uid, user_uuid);
465 /* If the user was not allowed to run the command we are done. */
466 if (!ISSET(validated, VALIDATE_OK)) {
467 if (ISSET(validated, FLAG_NO_USER | FLAG_NO_HOST)) {
468 audit_failure(NewArgv, "No user or host");
469 log_denial(validated, 1);
473 * We'd like to not leak path info at all here, but that can
474 * *really* confuse the users. To really close the leak we'd
475 * have to say "not allowed to run foo" even when the problem
476 * is just "no foo in path" since the user can trivially set
477 * their path to just contain a single dir.
479 log_denial(validated,
480 !(cmnd_status == NOT_FOUND_DOT || cmnd_status == NOT_FOUND));
481 if (cmnd_status == NOT_FOUND)
482 warningx("%s: command not found", user_cmnd);
483 else if (cmnd_status == NOT_FOUND_DOT)
484 warningx("ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run.", user_cmnd, user_cmnd, user_cmnd);
486 /* Just tell the user they are not allowed to run foo. */
487 log_denial(validated, 1);
489 audit_failure(NewArgv, "validation failure");
494 /* Create Ubuntu-style dot file to indicate sudo was successful. */
495 create_admin_success_flag();
497 /* Finally tell the user if the command did not exist. */
498 if (cmnd_status == NOT_FOUND_DOT) {
499 audit_failure(NewArgv, "command in current directory");
500 warningx("ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run.", user_cmnd, user_cmnd, user_cmnd);
502 } else if (cmnd_status == NOT_FOUND) {
503 audit_failure(NewArgv, "%s: command not found", user_cmnd);
504 warningx("%s: command not found", user_cmnd);
508 /* If user specified env vars make sure sudoers allows it. */
509 if (ISSET(sudo_mode, MODE_RUN) && !def_setenv) {
510 if (ISSET(sudo_mode, MODE_PRESERVE_ENV)) {
511 warningx("sorry, you are not allowed to preserve the environment");
514 validate_env_vars(sudo_user.env_vars);
517 if (ISSET(sudo_mode, (MODE_RUN | MODE_EDIT)) && (def_log_input || def_log_output)) {
518 if (def_iolog_file && def_iolog_dir) {
519 command_info[info_len++] = expand_iolog_path("iolog_path=",
520 def_iolog_dir, def_iolog_file, &sudo_user.iolog_file);
521 sudo_user.iolog_file++;
524 command_info[info_len++] = estrdup("iolog_stdin=true");
525 command_info[info_len++] = estrdup("iolog_ttyin=true");
527 if (def_log_output) {
528 command_info[info_len++] = estrdup("iolog_stdout=true");
529 command_info[info_len++] = estrdup("iolog_stderr=true");
530 command_info[info_len++] = estrdup("iolog_ttyout=true");
533 command_info[info_len++] = estrdup("iolog_compress=true");
536 log_allowed(validated);
537 if (ISSET(sudo_mode, MODE_CHECK))
538 rval = display_cmnd(snl, list_pw ? list_pw : sudo_user.pw);
539 else if (ISSET(sudo_mode, MODE_LIST))
540 display_privs(snl, list_pw ? list_pw : sudo_user.pw); /* XXX - return val */
542 /* Cleanup sudoers sources */
543 tq_foreach_fwd(snl, nss) {
546 if (def_group_plugin)
547 group_plugin_unload();
549 if (ISSET(sudo_mode, (MODE_VALIDATE|MODE_CHECK|MODE_LIST))) {
550 /* rval already set appropriately */
555 * Set umask based on sudoers.
556 * If user's umask is more restrictive, OR in those bits too
557 * unless umask_override is set.
559 if (def_umask != 0777) {
560 mode_t mask = def_umask;
561 if (!def_umask_override) {
562 mode_t omask = umask(mask);
566 easprintf(&command_info[info_len++], "umask=0%o", (unsigned int)mask);
569 if (ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
572 /* Convert /bin/sh -> -sh so shell knows it is a login shell */
573 if ((p = strrchr(NewArgv[0], '/')) == NULL)
578 /* Set cwd to run user's homedir. */
579 command_info[info_len++] = fmt_string("cwd", runas_pw->pw_dir);
581 #if defined(__linux__) || defined(_AIX)
582 /* Insert system-wide environment variables. */
583 read_env_file(_PATH_ENVIRONMENT, TRUE);
587 /* Insert system-wide environment variables. */
589 read_env_file(def_env_file, FALSE);
591 /* Insert user-specified environment variables. */
592 insert_env_vars(sudo_user.env_vars);
594 /* Restore signal handlers before we exec. */
595 (void) sigaction(SIGINT, &saved_sa_int, NULL);
596 (void) sigaction(SIGQUIT, &saved_sa_quit, NULL);
597 (void) sigaction(SIGTSTP, &saved_sa_tstp, NULL);
599 if (ISSET(sudo_mode, MODE_EDIT)) {
600 char *editor = find_editor(NewArgc - 1, NewArgv + 1, &edit_argv);
603 command_info[info_len++] = fmt_string("command", editor);
604 command_info[info_len++] = estrdup("sudoedit=true");
606 command_info[info_len++] = fmt_string("command", safe_cmnd);
608 if (def_stay_setuid) {
609 easprintf(&command_info[info_len++], "runas_uid=%u",
610 (unsigned int)user_uid);
611 easprintf(&command_info[info_len++], "runas_gid=%u",
612 (unsigned int)user_gid);
613 easprintf(&command_info[info_len++], "runas_euid=%u",
614 (unsigned int)runas_pw->pw_uid);
615 easprintf(&command_info[info_len++], "runas_egid=%u",
616 runas_gr ? (unsigned int)runas_gr->gr_gid :
617 (unsigned int)runas_pw->pw_gid);
619 easprintf(&command_info[info_len++], "runas_uid=%u",
620 (unsigned int)runas_pw->pw_uid);
621 easprintf(&command_info[info_len++], "runas_gid=%u",
622 runas_gr ? (unsigned int)runas_gr->gr_gid :
623 (unsigned int)runas_pw->pw_gid);
625 if (def_preserve_groups) {
626 command_info[info_len++] = "preserve_groups=true";
627 } else if (runas_ngroups != -1) {
632 glsize = sizeof("runas_groups=") - 1 + (runas_ngroups * (MAX_UID_T_LEN + 1));
633 gid_list = emalloc(glsize);
634 memcpy(gid_list, "runas_groups=", sizeof("runas_groups=") - 1);
635 cp = gid_list + sizeof("runas_groups=") - 1;
636 for (i = 0; i < runas_ngroups; i++) {
637 /* XXX - check rval */
638 len = snprintf(cp, glsize - (cp - gid_list), "%s%u",
639 i ? "," : "", (unsigned int) runas_groups[i]);
642 command_info[info_len++] = gid_list;
644 if (def_closefrom >= 0)
645 easprintf(&command_info[info_len++], "closefrom=%d", def_closefrom);
647 command_info[info_len++] = estrdup("noexec=true");
649 command_info[info_len++] = fmt_string("noexec_file", def_noexec_file);
651 command_info[info_len++] = estrdup("set_utmp=true");
653 command_info[info_len++] = fmt_string("utmp_user", runas_pw->pw_name);
654 #ifdef HAVE_LOGIN_CAP_H
656 command_info[info_len++] = fmt_string("login_class", lc->lc_class);
657 #endif /* HAVE_LOGIN_CAP_H */
659 if (user_role != NULL)
660 command_info[info_len++] = fmt_string("selinux_role", user_role);
661 if (user_type != NULL)
662 command_info[info_len++] = fmt_string("selinux_type", user_type);
663 #endif /* HAVE_SELINUX */
665 /* Must audit before uid change. */
666 audit_success(NewArgv);
668 *command_infop = command_info;
670 *argv_out = edit_argv ? edit_argv : NewArgv;
671 *user_env_out = env_get(); /* our private copy */
681 /* Close the password and group files and free up memory. */
689 sudoers_policy_check(int argc, char * const argv[], char *env_add[],
690 char **command_infop[], char **argv_out[], char **user_env_out[])
692 if (!ISSET(sudo_mode, MODE_EDIT))
693 SET(sudo_mode, MODE_RUN);
695 return sudoers_policy_main(argc, argv, 0, env_add, command_infop,
696 argv_out, user_env_out);
700 sudoers_policy_validate(void)
702 user_cmnd = "validate";
703 SET(sudo_mode, MODE_VALIDATE);
705 return sudoers_policy_main(0, NULL, I_VERIFYPW, NULL, NULL, NULL, NULL);
709 sudoers_policy_invalidate(int remove)
712 if (sigsetjmp(error_jmp, 1) == 0) {
713 remove_timestamp(remove);
719 sudoers_policy_list(int argc, char * const argv[], int verbose,
720 const char *list_user)
726 SET(sudo_mode, MODE_CHECK);
728 SET(sudo_mode, MODE_LIST);
732 list_pw = sudo_getpwnam(list_user);
733 if (list_pw == NULL) {
734 warningx("unknown user: %s", list_user);
738 rval = sudoers_policy_main(argc, argv, I_LISTPW, NULL, NULL, NULL, NULL);
748 * Initialize timezone, set umask, fill in ``sudo_user'' struct and
749 * load the ``interfaces'' array.
752 init_vars(char * const envp[])
757 (void) tzset(); /* set the timezone if applicable */
758 #endif /* HAVE_TZSET */
760 for (ep = envp; *ep; ep++) {
761 /* XXX - don't fill in if empty string */
764 if (strncmp("KRB5CCNAME=", *ep, 11) == 0)
765 user_ccname = *ep + 11;
768 if (strncmp("PATH=", *ep, 5) == 0)
772 if (!user_prompt && strncmp("SUDO_PROMPT=", *ep, 12) == 0)
773 user_prompt = *ep + 12;
774 else if (strncmp("SUDO_USER=", *ep, 10) == 0)
775 prev_user = *ep + 10;
781 * Get a local copy of the user's struct passwd with the shadow password
782 * if necessary. It is assumed that euid is 0 at this point so we
783 * can read the shadow passwd file if necessary.
785 if ((sudo_user.pw = sudo_getpwnam(user_name)) == NULL) {
788 /* Create a fake struct passwd for log_error(). */
789 memset(&pw, 0, sizeof(pw));
790 pw.pw_uid = getuid();
791 pw.pw_name = user_name;
795 * It is not unusual for users to place "sudo -k" in a .logout
796 * file which can cause sudo to be run during reboot after the
797 * YP/NIS/NIS+/LDAP/etc daemon has died.
799 if (sudo_mode == MODE_KILL || sudo_mode == MODE_INVALIDATE)
800 errorx(1, "unknown user: %s", user_name);
801 log_error(0, "unknown user: %s", user_name);
804 #ifdef HAVE_MBR_CHECK_MEMBERSHIP
805 mbr_uid_to_uuid(user_uid, user_uuid);
808 /* It is now safe to use log_error() and set_perms() */
812 * Fill in user_cmnd, user_args, user_base and user_stat variables
813 * and apply any command-specific defaults entries.
816 set_cmnd(int sudo_mode)
819 char *path = user_path;
821 /* Resolve the path and return. */
823 user_stat = emalloc(sizeof(struct stat));
825 /* Default value for cmnd, overridden below. */
826 if (user_cmnd == NULL)
827 user_cmnd = NewArgv[0];
829 if (sudo_mode & (MODE_RUN | MODE_EDIT | MODE_CHECK)) {
830 if (ISSET(sudo_mode, MODE_RUN | MODE_CHECK)) {
831 if (def_secure_path && !user_is_exempt())
832 path = def_secure_path;
833 set_perms(PERM_RUNAS);
834 rval = find_path(NewArgv[0], &user_cmnd, user_stat, path,
838 /* Failed as root, try as invoking user. */
839 set_perms(PERM_USER);
840 rval = find_path(NewArgv[0], &user_cmnd, user_stat, path,
851 /* Alloc and build up user_args. */
852 for (size = 0, from = NewArgv + 1; *from; from++)
853 size += strlen(*from) + 1;
854 user_args = emalloc(size);
855 for (to = user_args, from = NewArgv + 1; *from; from++) {
856 n = strlcpy(to, *from, size - (to - user_args));
857 if (n >= size - (to - user_args))
858 errorx(1, "internal error, set_cmnd() overflow");
865 if (strlen(user_cmnd) >= PATH_MAX)
866 errorx(1, "%s: file name too long", user_cmnd);
868 if ((user_base = strrchr(user_cmnd, '/')) != NULL)
871 user_base = user_cmnd;
873 if (!update_defaults(SETDEF_CMND))
874 log_error(NO_STDERR|NO_EXIT, "problem with defaults entries");
876 if (!runas_user && !runas_group)
877 set_runaspw(def_runas_default); /* may have been updated above */
883 * Open sudoers and sanity check mode/owner/type.
884 * Returns a handle to the sudoers file or NULL on error.
887 open_sudoers(const char *sudoers, int doedit, int *keepopen)
894 * Fix the mode and group on sudoers file from old default.
895 * Only works if file system is readable/writable by root.
897 if ((rootstat = stat_sudoers(sudoers, &statbuf)) == 0 &&
898 sudoers_uid == statbuf.st_uid && sudoers_mode != 0400 &&
899 (statbuf.st_mode & 0007777) == 0400) {
901 if (chmod(sudoers, sudoers_mode) == 0) {
902 warningx("fixed mode on %s", sudoers);
903 SET(statbuf.st_mode, sudoers_mode);
904 if (statbuf.st_gid != sudoers_gid) {
905 if (chown(sudoers, (uid_t) -1, sudoers_gid) == 0) {
906 warningx("set group on %s", sudoers);
907 statbuf.st_gid = sudoers_gid;
909 warning("unable to set group on %s", sudoers);
912 warning("unable to fix mode on %s", sudoers);
916 * Sanity checks on sudoers file. Must be done as sudoers
917 * file owner. We already did a stat as root, so use that
918 * data if we can't stat as sudoers file owner.
920 set_perms(PERM_SUDOERS);
922 if (rootstat != 0 && stat_sudoers(sudoers, &statbuf) != 0)
923 log_error(USE_ERRNO|NO_EXIT, "can't stat %s", sudoers);
924 else if (!S_ISREG(statbuf.st_mode))
925 log_error(NO_EXIT, "%s is not a regular file", sudoers);
926 else if ((statbuf.st_mode & 07577) != sudoers_mode)
927 log_error(NO_EXIT, "%s is mode 0%o, should be 0%o", sudoers,
928 (unsigned int) (statbuf.st_mode & 07777),
929 (unsigned int) sudoers_mode);
930 else if (statbuf.st_uid != sudoers_uid)
931 log_error(NO_EXIT, "%s is owned by uid %u, should be %u", sudoers,
932 (unsigned int) statbuf.st_uid, (unsigned int) sudoers_uid);
933 else if (statbuf.st_gid != sudoers_gid)
934 log_error(NO_EXIT, "%s is owned by gid %u, should be %u", sudoers,
935 (unsigned int) statbuf.st_gid, (unsigned int) sudoers_gid);
936 else if ((fp = fopen(sudoers, "r")) == NULL)
937 log_error(USE_ERRNO|NO_EXIT, "can't open %s", sudoers);
940 * Make sure we can actually read sudoers so we can present the
941 * user with a reasonable error message (unlike the lexer).
943 if (statbuf.st_size != 0 && fgetc(fp) == EOF) {
944 log_error(USE_ERRNO|NO_EXIT, "can't read %s", sudoers);
952 (void) fcntl(fileno(fp), F_SETFD, 1);
955 restore_perms(); /* change back to root */
959 #ifdef HAVE_LOGIN_CAP_H
961 set_loginclass(struct passwd *pw)
966 * Don't make it a fatal error if the user didn't specify the login
967 * class themselves. We do this because if login.conf gets
968 * corrupted we want the admin to be able to use sudo to fix it.
971 errflags = NO_MAIL|MSG_ONLY;
973 errflags = NO_MAIL|MSG_ONLY|NO_EXIT;
975 if (login_class && strcmp(login_class, "-") != 0) {
977 strcmp(runas_user ? runas_user : def_runas_default, "root") != 0)
978 errorx(1, "only root can use -c %s", login_class);
980 login_class = pw->pw_class;
981 if (!login_class || !*login_class)
983 (pw->pw_uid == 0) ? LOGIN_DEFROOTCLASS : LOGIN_DEFCLASS;
986 lc = login_getclass(login_class);
987 if (!lc || !lc->lc_class || strcmp(lc->lc_class, login_class) != 0) {
988 log_error(errflags, "unknown login class: %s", login_class);
990 lc = login_getclass(NULL); /* needed for login_getstyle() later */
995 set_loginclass(struct passwd *pw)
998 #endif /* HAVE_LOGIN_CAP_H */
1001 * Look up the fully qualified domain name and set user_host and user_shost.
1006 #ifdef HAVE_GETADDRINFO
1007 struct addrinfo *res0, hint;
1013 #ifdef HAVE_GETADDRINFO
1014 zero_bytes(&hint, sizeof(hint));
1015 hint.ai_family = PF_UNSPEC;
1016 hint.ai_flags = AI_CANONNAME;
1017 if (getaddrinfo(user_host, NULL, &hint, &res0) != 0) {
1019 if (!(hp = gethostbyname(user_host))) {
1021 log_error(MSG_ONLY|NO_EXIT,
1022 "unable to resolve host %s", user_host);
1024 if (user_shost != user_host)
1027 #ifdef HAVE_GETADDRINFO
1028 user_host = estrdup(res0->ai_canonname);
1031 user_host = estrdup(hp->h_name);
1034 if ((p = strchr(user_host, '.')) != NULL)
1035 user_shost = estrndup(user_host, (size_t)(p - user_host));
1037 user_shost = user_host;
1041 * Get passwd entry for the user we are going to run commands as
1042 * and store it in runas_pw. By default, commands run as "root".
1045 set_runaspw(char *user)
1047 if (runas_pw != NULL)
1048 pw_delref(runas_pw);
1050 if ((runas_pw = sudo_getpwuid(atoi(user + 1))) == NULL)
1051 runas_pw = sudo_fakepwnam(user, runas_gr ? runas_gr->gr_gid : 0);
1053 if ((runas_pw = sudo_getpwnam(user)) == NULL) {
1054 audit_failure(NewArgv, "unknown user: %s", user);
1055 log_error(NO_MAIL|MSG_ONLY, "unknown user: %s", user);
1061 * Get group entry for the group we are going to run commands as
1062 * and store it in runas_gr.
1065 set_runasgr(char *group)
1067 if (runas_gr != NULL)
1068 gr_delref(runas_gr);
1069 if (*group == '#') {
1070 if ((runas_gr = sudo_getgrgid(atoi(group + 1))) == NULL)
1071 runas_gr = sudo_fakegrnam(group);
1073 if ((runas_gr = sudo_getgrnam(group)) == NULL)
1074 log_error(NO_MAIL|MSG_ONLY, "unknown group: %s", group);
1079 * Cleanup hook for error()/errorx()
1082 plugin_cleanup(int gotsignal)
1084 struct sudo_nss *nss;
1088 tq_foreach_fwd(snl, nss)
1091 if (def_group_plugin)
1092 group_plugin_unload();
1099 sudoers_policy_version(int verbose)
1101 if (sigsetjmp(error_jmp, 1)) {
1102 /* error recovery via error(), errorx() or log_error() */
1106 sudo_printf(SUDO_CONV_INFO_MSG, "Sudoers policy plugin version %s\n",
1108 sudo_printf(SUDO_CONV_INFO_MSG, "Sudoers file grammar version %d\n",
1109 SUDOERS_GRAMMAR_VERSION);
1112 sudo_printf(SUDO_CONV_INFO_MSG, "\nSudoers path: %s\n", sudoers_file);
1114 # ifdef _PATH_NSSWITCH_CONF
1115 sudo_printf(SUDO_CONV_INFO_MSG, "nsswitch path: %s\n", _PATH_NSSWITCH_CONF);
1117 sudo_printf(SUDO_CONV_INFO_MSG, "ldap.conf path: %s\n", _PATH_LDAP_CONF);
1118 sudo_printf(SUDO_CONV_INFO_MSG, "ldap.secret path: %s\n", _PATH_LDAP_SECRET);
1120 dump_auth_methods();
1122 sudo_printf(SUDO_CONV_INFO_MSG, "\n");
1123 dump_interfaces(interfaces_string);
1124 sudo_printf(SUDO_CONV_INFO_MSG, "\n");
1130 deserialize_info(char * const settings[], char * const user_info[])
1136 #define MATCHES(s, v) (strncmp(s, v, sizeof(v) - 1) == 0)
1138 /* Parse command line settings. */
1139 user_closefrom = -1;
1140 for (cur = settings; *cur != NULL; cur++) {
1141 if (MATCHES(*cur, "closefrom=")) {
1142 user_closefrom = atoi(*cur + sizeof("closefrom=") - 1);
1145 if (MATCHES(*cur, "debug_level=")) {
1146 debug_level = atoi(*cur + sizeof("debug_level=") - 1);
1149 if (MATCHES(*cur, "runas_user=")) {
1150 runas_user = *cur + sizeof("runas_user=") - 1;
1153 if (MATCHES(*cur, "runas_group=")) {
1154 runas_group = *cur + sizeof("runas_group=") - 1;
1157 if (MATCHES(*cur, "prompt=")) {
1158 user_prompt = *cur + sizeof("prompt=") - 1;
1159 def_passprompt_override = TRUE;
1162 if (MATCHES(*cur, "set_home=")) {
1163 if (atobool(*cur + sizeof("set_home=") - 1) == TRUE)
1164 SET(flags, MODE_RESET_HOME);
1167 if (MATCHES(*cur, "preserve_environment=")) {
1168 if (atobool(*cur + sizeof("preserve_environment=") - 1) == TRUE)
1169 SET(flags, MODE_PRESERVE_ENV);
1172 if (MATCHES(*cur, "run_shell=")) {
1173 if (atobool(*cur + sizeof("run_shell=") - 1) == TRUE)
1174 SET(flags, MODE_SHELL);
1177 if (MATCHES(*cur, "login_shell=")) {
1178 if (atobool(*cur + sizeof("login_shell=") - 1) == TRUE) {
1179 SET(flags, MODE_LOGIN_SHELL);
1180 def_env_reset = TRUE;
1184 if (MATCHES(*cur, "implied_shell=")) {
1185 if (atobool(*cur + sizeof("implied_shell=") - 1) == TRUE)
1186 SET(flags, MODE_IMPLIED_SHELL);
1189 if (MATCHES(*cur, "preserve_groups=")) {
1190 if (atobool(*cur + sizeof("preserve_groups=") - 1) == TRUE)
1191 SET(flags, MODE_PRESERVE_GROUPS);
1194 if (MATCHES(*cur, "ignore_ticket=")) {
1195 if (atobool(*cur + sizeof("ignore_ticket=") - 1) == TRUE)
1196 SET(flags, MODE_IGNORE_TICKET);
1199 if (MATCHES(*cur, "noninteractive=")) {
1200 if (atobool(*cur + sizeof("noninteractive=") - 1) == TRUE)
1201 SET(flags, MODE_NONINTERACTIVE);
1204 if (MATCHES(*cur, "sudoedit=")) {
1205 if (atobool(*cur + sizeof("sudoedit=") - 1) == TRUE)
1206 SET(flags, MODE_EDIT);
1209 if (MATCHES(*cur, "login_class=")) {
1210 login_class = *cur + sizeof("login_class=") - 1;
1211 def_use_loginclass = TRUE;
1215 if (MATCHES(*cur, "selinux_role=")) {
1216 user_role = *cur + sizeof("selinux_role=") - 1;
1219 if (MATCHES(*cur, "selinux_type=")) {
1220 user_type = *cur + sizeof("selinux_type=") - 1;
1223 #endif /* HAVE_SELINUX */
1224 #ifdef HAVE_BSD_AUTH_H
1225 if (MATCHES(*cur, "bsdauth_type=")) {
1226 login_style = *cur + sizeof("bsdauth_type=") - 1;
1229 #endif /* HAVE_BSD_AUTH_H */
1230 #if !defined(HAVE_GETPROGNAME) && !defined(HAVE___PROGNAME)
1231 if (MATCHES(*cur, "progname=")) {
1232 setprogname(*cur + sizeof("progname=") - 1);
1236 if (MATCHES(*cur, "network_addrs=")) {
1237 interfaces_string = *cur + sizeof("network_addrs=") - 1;
1238 set_interfaces(interfaces_string);
1241 if (MATCHES(*cur, "sudoers_file=")) {
1242 sudoers_file = *cur + sizeof("sudoers_file=") - 1;
1245 if (MATCHES(*cur, "sudoers_uid=")) {
1246 sudoers_uid = (uid_t) atoi(*cur + sizeof("sudoers_uid=") - 1);
1249 if (MATCHES(*cur, "sudoers_gid=")) {
1250 sudoers_gid = (gid_t) atoi(*cur + sizeof("sudoers_gid=") - 1);
1253 if (MATCHES(*cur, "sudoers_mode=")) {
1254 sudoers_mode = (mode_t) strtol(*cur + sizeof("sudoers_mode=") - 1,
1260 for (cur = user_info; *cur != NULL; cur++) {
1261 if (MATCHES(*cur, "user=")) {
1262 user_name = estrdup(*cur + sizeof("user=") - 1);
1265 if (MATCHES(*cur, "uid=")) {
1266 user_uid = (uid_t) atoi(*cur + sizeof("uid=") - 1);
1269 if (MATCHES(*cur, "gid=")) {
1270 user_gid = (gid_t) atoi(*cur + sizeof("gid=") - 1);
1273 if (MATCHES(*cur, "groups=")) {
1274 /* Count number of groups */
1275 const char *val = *cur + sizeof("groups=") - 1;
1277 if (val[0] != '\0') {
1279 for (cp = val; *cp != '\0'; cp++) {
1284 user_groups = emalloc2(user_ngroups, sizeof(GETGROUPS_T));
1288 /* XXX - strtol would be better here */
1289 user_groups[user_ngroups++] = atoi(cp);
1290 cp = strchr(cp, ',');
1293 cp++; /* skip over comma */
1298 if (MATCHES(*cur, "cwd=")) {
1299 user_cwd = estrdup(*cur + sizeof("cwd=") - 1);
1302 if (MATCHES(*cur, "tty=")) {
1303 user_tty = user_ttypath = estrdup(*cur + sizeof("tty=") - 1);
1304 if (strncmp(user_tty, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
1305 user_tty += sizeof(_PATH_DEV) - 1;
1308 if (MATCHES(*cur, "host=")) {
1309 user_host = user_shost = estrdup(*cur + sizeof("host=") - 1);
1310 if ((p = strchr(user_host, '.')))
1311 user_shost = estrndup(user_host, (size_t)(p - user_host));
1314 if (MATCHES(*cur, "lines=")) {
1315 sudo_user.lines = atoi(*cur + sizeof("lines=") - 1);
1318 if (MATCHES(*cur, "cols=")) {
1319 sudo_user.cols = atoi(*cur + sizeof("cols=") - 1);
1323 if (user_cwd == NULL)
1324 user_cwd = "unknown";
1325 if (user_tty == NULL)
1326 user_tty = "unknown"; /* user_ttypath remains NULL */
1333 resolve_editor(char *editor, int nfiles, char **files, char ***argv_out)
1335 char *cp, **nargv, *editor_path = NULL;
1336 int ac, i, nargc, wasblank;
1338 editor = estrdup(editor); /* becomes part of argv_out */
1341 * Split editor into an argument vector; editor is reused (do not free).
1342 * The EDITOR and VISUAL environment variables may contain command
1343 * line args so look for those and alloc space for them too.
1346 for (wasblank = FALSE, cp = editor; *cp != '\0'; cp++) {
1347 if (isblank((unsigned char) *cp))
1349 else if (wasblank) {
1354 /* If we can't find the editor in the user's PATH, give up. */
1355 cp = strtok(editor, " \t");
1357 find_path(cp, &editor_path, NULL, getenv("PATH"), 0) != FOUND) {
1361 nargv = (char **) emalloc2(nargc + 1 + nfiles + 1, sizeof(char *));
1362 for (ac = 0; cp != NULL && ac < nargc; ac++) {
1364 cp = strtok(NULL, " \t");
1367 for (i = 0; i < nfiles; )
1368 nargv[ac++] = files[i++];
1376 * Determine which editor to use. We don't need to worry about restricting
1377 * this to a "safe" editor since it runs with the uid of the invoking user,
1378 * not the runas (privileged) user.
1381 find_editor(int nfiles, char **files, char ***argv_out)
1383 char *cp, *editor, *editor_path = NULL, **ev, *ev0[4];
1386 * If any of SUDO_EDITOR, VISUAL or EDITOR are set, choose the first one.
1388 ev0[0] = "SUDO_EDITOR";
1392 for (ev = ev0; *ev != NULL; ev++) {
1393 if ((editor = getenv(*ev)) != NULL && *editor != '\0') {
1394 editor_path = resolve_editor(editor, nfiles, files, argv_out);
1395 if (editor_path != NULL)
1399 if (editor_path == NULL) {
1400 /* def_editor could be a path, split it up */
1401 editor = estrdup(def_editor);
1402 cp = strtok(editor, ":");
1403 while (cp != NULL && editor_path == NULL) {
1404 editor_path = resolve_editor(cp, nfiles, files, argv_out);
1405 cp = strtok(NULL, ":");
1411 audit_failure(NewArgv, "%s: command not found", editor);
1412 warningx("%s: command not found", editor);
1417 #ifdef USE_ADMIN_FLAG
1419 create_admin_success_flag(void)
1421 struct stat statbuf;
1422 char flagfile[PATH_MAX];
1425 /* Check whether the user is in the admin group. */
1426 if (!user_in_group(sudo_user.pw, "admin"))
1429 /* Build path to flag file. */
1430 n = snprintf(flagfile, sizeof(flagfile), "%s/.sudo_as_admin_successful",
1432 if (n <= 0 || n >= sizeof(flagfile))
1435 /* Create admin flag file if it doesn't already exist. */
1436 set_perms(PERM_USER);
1437 if (stat(flagfile, &statbuf) != 0) {
1438 fd = open(flagfile, O_CREAT|O_WRONLY|O_EXCL, 0644);
1443 #else /* !USE_ADMIN_FLAG */
1445 create_admin_success_flag(void)
1449 #endif /* USE_ADMIN_FLAG */
1451 struct policy_plugin sudoers_policy = {
1454 sudoers_policy_open,
1455 sudoers_policy_close,
1456 sudoers_policy_version,
1457 sudoers_policy_check,
1458 sudoers_policy_list,
1459 sudoers_policy_validate,
1460 sudoers_policy_invalidate,
1461 sudoers_policy_init_session