Commit message: su: properly clear child PID

Reported-by: Tobias Stöckmann <tobias@stoeckmann.org>
Signed-off-by: Karel Zak <kzak@redhat.com>
CVE: CVE-2017-2616
CWE: CWE-362
Vulnerability description: A race condition was found in util-linux before 2.32.1 in the way su handled the management of child processes. A local authenticated attacker could use this flaw to kill other processes with root privileges under specific conditions.

Project: util-linux
File: su-common.c

add_supp_group(const char *name, gid_t **groups, size_t *ngroups)
{
  struct group *gr;

  if (*ngroups >= NGROUPS_MAX)
    errx(EXIT_FAILURE,
	P_("specifying more than %d supplemental group is not possible",
	   "specifying more than %d supplemental groups is not possible",
	     NGROUPS_MAX - 1), NGROUPS_MAX - 1);

  gr = getgrnam(name);
  if (!gr)
    errx(EXIT_FAILURE, _("group %s does not exist"), name);

  *groups = xrealloc(*groups, sizeof(gid_t) * (*ngroups + 1));
  (*groups)[*ngroups] = gr->gr_gid;
  (*ngroups)++;

  return gr->gr_gid;
}

Project: util-linux
File: su-common.c

authenticate (const struct passwd *pw)
{
  const struct passwd *lpw = NULL;
  const char *cp, *srvname = NULL;
  int retval;

  switch (su_mode) {
  case SU_MODE:
    srvname = simulate_login ? PAM_SRVNAME_SU_L : PAM_SRVNAME_SU;
    break;
  case RUNUSER_MODE:
    srvname = simulate_login ? PAM_SRVNAME_RUNUSER_L : PAM_SRVNAME_RUNUSER;
    break;
  default:
    abort();
    break;
  }

  retval = pam_start (srvname, pw->pw_name, &conv, &pamh);
  if (is_pam_failure(retval))
    goto done;

  if (isatty (0) && (cp = ttyname (0)) != NULL)
    {
      const char *tty;

      if (strncmp (cp, "/dev/", 5) == 0)
	tty = cp + 5;
      else
	tty = cp;
      retval = pam_set_item (pamh, PAM_TTY, tty);
      if (is_pam_failure(retval))
	goto done;
    }

  lpw = current_getpwuid ();
  if (lpw && lpw->pw_name)
    {
      retval = pam_set_item (pamh, PAM_RUSER, (const void *) lpw->pw_name);
      if (is_pam_failure(retval))
	goto done;
    }

  if (su_mode == RUNUSER_MODE)
    {
      /*
       * This is the only difference between runuser(1) and su(1). The command
       * runuser(1) does not required authentication, because user is root.
       */
      if (restricted)
	errx(EXIT_FAILURE, _("may not be used by non-root users"));
      return;
    }

  retval = pam_authenticate (pamh, 0);
  if (is_pam_failure(retval))
    goto done;

  retval = pam_acct_mgmt (pamh, 0);
  if (retval == PAM_NEW_AUTHTOK_REQD)
    {
      /* Password has expired.  Offer option to change it.  */
      retval = pam_chauthtok (pamh, PAM_CHANGE_EXPIRED_AUTHTOK);
    }

done:

  log_syslog(pw, !is_pam_failure(retval));

  if (is_pam_failure(retval))
    {
      const char *msg;

      log_btmp(pw);

      msg  = pam_strerror(pamh, retval);
      pam_end(pamh, retval);
      sleep (getlogindefs_num ("FAIL_DELAY", 1));
      errx (EXIT_FAILURE, "%s", msg?msg:_("incorrect password"));
    }
}

Project: util-linux
File: su-common.c

change_identity (const struct passwd *pw)
{
  if (setgid (pw->pw_gid))
    err (EXIT_FAILURE,  _("cannot set group id"));
  if (setuid (pw->pw_uid))
    err (EXIT_FAILURE,  _("cannot set user id"));
}

Project: util-linux
File: su-common.c

current_getpwuid(void)
{
  uid_t ruid;

  /* GNU Hurd implementation has an extension where a process can exist in a
   * non-conforming environment, and thus be outside the realms of POSIX
   * process identifiers; on this platform, getuid() fails with a status of
   * (uid_t)(-1) and sets errno if a program is run from a non-conforming
   * environment.
   *
   * http://austingroupbugs.net/view.php?id=511
   */
  errno = 0;
  ruid = getuid ();

  return errno == 0 ? getpwuid (ruid) : NULL;
}

Project: util-linux
File: su-common.c

evaluate_uid(void)
{
  uid_t ruid = getuid();
  uid_t euid = geteuid();

  /* if we're really root and aren't running setuid */
  return (uid_t) 0 == ruid && ruid == euid ? 0 : 1;
}

Project: util-linux
File: su-common.c

export_pamenv (void)
{
  char **env;

  /* This is a copy but don't care to free as we exec later anyways.  */
  env = pam_getenvlist (pamh);
  while (env && *env)
    {
      if (putenv (*env) != 0)
	err (EXIT_FAILURE, NULL);
      env++;
    }
}

Project: util-linux
File: su-common.c

static void log_btmp(struct passwd const *pw)
{
	struct utmpx ut;
	struct timeval tv;
	const char *tty_name, *tty_num;

	memset(&ut, 0, sizeof(ut));

	strncpy(ut.ut_user,
		pw && pw->pw_name ? pw->pw_name : "(unknown)",
		sizeof(ut.ut_user));

	get_terminal_name(NULL, &tty_name, &tty_num);
	if (tty_num)
		xstrncpy(ut.ut_id, tty_num, sizeof(ut.ut_id));
	if (tty_name)
		xstrncpy(ut.ut_line, tty_name, sizeof(ut.ut_line));

	gettimeofday(&tv, NULL);
	ut.ut_tv.tv_sec = tv.tv_sec;
	ut.ut_tv.tv_usec = tv.tv_usec;
	ut.ut_type = LOGIN_PROCESS;	/* XXX doesn't matter */
	ut.ut_pid = getpid();

	updwtmpx(_PATH_BTMP, &ut);
}

Project: util-linux
File: su-common.c

log_syslog(struct passwd const *pw, bool successful)
{
  const char *new_user, *old_user, *tty;

  new_user = pw->pw_name;
  /* The utmp entry (via getlogin) is probably the best way to identify
     the user, especially if someone su's from a su-shell.  */
  old_user = getlogin ();
  if (!old_user)
    {
      /* getlogin can fail -- usually due to lack of utmp entry.
	 Resort to getpwuid.  */
      struct passwd *pwd = current_getpwuid();
      old_user = pwd ? pwd->pw_name : "";
    }

  if (get_terminal_name(NULL, &tty, NULL) != 0 || !tty)
    tty = "none";

  openlog (program_invocation_short_name, 0 , LOG_AUTH);
  syslog (LOG_NOTICE, "%s(to %s) %s on %s",
	  successful ? "" :
	  su_mode == RUNUSER_MODE ? "FAILED RUNUSER " : "FAILED SU ",
	  new_user, old_user, tty);
  closelog ();
}

Project: util-linux
File: su-common.c

modify_environment (const struct passwd *pw, const char *shell)
{
  if (simulate_login)
    {
      /* Leave TERM unchanged.  Set HOME, SHELL, USER, LOGNAME, PATH.
         Unset all other environment variables.  */
      char *term = getenv ("TERM");
      if (term)
	term = xstrdup (term);
      environ = xmalloc ((6 + !!term) * sizeof (char *));
      environ[0] = NULL;
      if (term) {
	xsetenv ("TERM", term, 1);
	free(term);
      }
      xsetenv ("HOME", pw->pw_dir, 1);
      if (shell)
	xsetenv ("SHELL", shell, 1);
      xsetenv ("USER", pw->pw_name, 1);
      xsetenv ("LOGNAME", pw->pw_name, 1);
      set_path(pw);
    }
  else
    {
      /* Set HOME, SHELL, and (if not becoming a superuser)
	 USER and LOGNAME.  */
      if (change_environment)
        {
          xsetenv ("HOME", pw->pw_dir, 1);
	  if (shell)
            xsetenv ("SHELL", shell, 1);
	  if (getlogindefs_bool ("ALWAYS_SET_PATH", 0))
	    set_path(pw);

          if (pw->pw_uid)
            {
              xsetenv ("USER", pw->pw_name, 1);
              xsetenv ("LOGNAME", pw->pw_name, 1);
            }
        }
    }

  export_pamenv ();
}

Project: util-linux
File: su-common.c

set_path(const struct passwd* pw)
{
  int r;
  if (pw->pw_uid)
    r = logindefs_setenv("PATH", "ENV_PATH", _PATH_DEFPATH);

  else if ((r = logindefs_setenv("PATH", "ENV_ROOTPATH", NULL)) != 0)
    r = logindefs_setenv("PATH", "ENV_SUPATH", _PATH_DEFPATH_ROOT);

  if (r != 0)
    err (EXIT_FAILURE,  _("failed to set the %s environment variable"), "PATH");
}

Project: util-linux
File: su-common.c

su_catch_sig (int sig)
{
  caught_signal = sig;
}

Project: util-linux
File: su-common.c

su_main (int argc, char **argv, int mode)
{
  int optc;
  const char *new_user = DEFAULT_USER, *runuser_user = NULL;
  char *command = NULL;
  int request_same_session = 0;
  char *shell = NULL;
  struct passwd *pw;
  struct passwd pw_copy;

  gid_t *groups = NULL;
  size_t ngroups = 0;
  bool use_supp = false;
  bool use_gid = false;
  gid_t gid = 0;

  static const struct option longopts[] = {
    {"command", required_argument, NULL, 'c'},
    {"session-command", required_argument, NULL, 'C'},
    {"fast", no_argument, NULL, 'f'},
    {"login", no_argument, NULL, 'l'},
    {"preserve-environment", no_argument, NULL, 'p'},
    {"shell", required_argument, NULL, 's'},
    {"group", required_argument, NULL, 'g'},
    {"supp-group", required_argument, NULL, 'G'},
    {"user", required_argument, NULL, 'u'},		/* runuser only */
    {"help", no_argument, 0, 'h'},
    {"version", no_argument, 0, 'V'},
    {NULL, 0, NULL, 0}
  };

  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);
  atexit(close_stdout);

  su_mode = mode;
  fast_startup = false;
  simulate_login = false;
  change_environment = true;

  while ((optc = getopt_long (argc, argv, "c:fg:G:lmps:u:hV", longopts, NULL)) != -1)
    {
      switch (optc)
	{
	case 'c':
	  command = optarg;
	  break;

        case 'C':
          command = optarg;
          request_same_session = 1;
          break;

	case 'f':
	  fast_startup = true;
	  break;

	case 'g':
	  use_gid = true;
	  gid = add_supp_group(optarg, &groups, &ngroups);
	  break;

	case 'G':
	  use_supp = true;
	  add_supp_group(optarg, &groups, &ngroups);
	  break;

	case 'l':
	  simulate_login = true;
	  break;

	case 'm':
	case 'p':
	  change_environment = false;
	  break;

	case 's':
	  shell = optarg;
	  break;

	case 'u':
	  if (su_mode != RUNUSER_MODE)
	    usage (EXIT_FAILURE);
	  runuser_user = optarg;
	  break;

	case 'h':
	  usage(0);

	case 'V':
	  printf(UTIL_LINUX_VERSION);
	  exit(EXIT_SUCCESS);

	default:
	  errtryhelp(EXIT_FAILURE);
	}
    }

  restricted = evaluate_uid ();

  if (optind < argc && !strcmp (argv[optind], "-"))
    {
      simulate_login = true;
      ++optind;
    }

  if (simulate_login && !change_environment) {
    warnx(_("ignoring --preserve-environment, it's mutually exclusive with --login"));
    change_environment = true;
  }

  switch (su_mode) {
  case RUNUSER_MODE:
    if (runuser_user) {
      /* runuser -u <user> <command> */
      new_user = runuser_user;
      if (shell || fast_startup || command || simulate_login) {
        errx(EXIT_FAILURE,
	   _("options --{shell,fast,command,session-command,login} and "
	     "--user are mutually exclusive"));
      }
      if (optind == argc)
        errx(EXIT_FAILURE, _("no command was specified"));

      break;
    }
    /* fallthrough if -u <user> is not specified, then follow
     * traditional su(1) behavior
     */
  case SU_MODE:
    if (optind < argc)
      new_user = argv[optind++];
    break;
  }

  if ((use_supp || use_gid) && restricted)
    errx(EXIT_FAILURE, _("only root can specify alternative groups"));

  logindefs_load_defaults = load_config;

  pw = getpwnam (new_user);
  if (! (pw && pw->pw_name && pw->pw_name[0] && pw->pw_dir && pw->pw_dir[0]
	 && pw->pw_passwd))
    errx (EXIT_FAILURE, _("user %s does not exist"), new_user);

  /* Make a copy of the password information and point pw at the local
     copy instead.  Otherwise, some systems (e.g. Linux) would clobber
     the static data through the getlogin call from log_su.
     Also, make sure pw->pw_shell is a nonempty string.
     It may be NULL when NEW_USER is a username that is retrieved via NIS (YP),
     but that doesn't have a default shell listed.  */
  pw_copy = *pw;
  pw = &pw_copy;
  pw->pw_name = xstrdup (pw->pw_name);
  pw->pw_passwd = xstrdup (pw->pw_passwd);
  pw->pw_dir = xstrdup (pw->pw_dir);
  pw->pw_shell = xstrdup (pw->pw_shell && pw->pw_shell[0]
			  ? pw->pw_shell
			  : DEFAULT_SHELL);
  endpwent ();

  if (use_supp && !use_gid)
    pw->pw_gid = groups[0];
  else if (use_gid)
    pw->pw_gid = gid;

  authenticate (pw);

  if (request_same_session || !command || !pw->pw_uid)
    same_session = 1;

  /* initialize shell variable only if "-u <user>" not specified */
  if (runuser_user) {
    shell = NULL;
  } else {
    if (!shell && !change_environment)
      shell = getenv ("SHELL");
    if (shell && getuid () != 0 && restricted_shell (pw->pw_shell))
      {
	/* The user being su'd to has a nonstandard shell, and so is
	   probably a uucp account or has restricted access.  Don't
	   compromise the account by allowing access with a standard
	   shell.  */
	warnx (_("using restricted shell %s"), pw->pw_shell);
	shell = NULL;
      }
    shell = xstrdup (shell ? shell : pw->pw_shell);
  }

  init_groups (pw, groups, ngroups);

  if (!simulate_login || command)
    suppress_pam_info = 1;		/* don't print PAM info messages */

  create_watching_parent ();
  /* Now we're in the child.  */

  change_identity (pw);
  if (!same_session)
    setsid ();

  /* Set environment after pam_open_session, which may put KRB5CCNAME
     into the pam_env, etc.  */

  modify_environment (pw, shell);

  if (simulate_login && chdir (pw->pw_dir) != 0)
    warn (_("warning: cannot change directory to %s"), pw->pw_dir);

  if (shell)
    run_shell (shell, command, argv + optind, max (0, argc - optind));
  else {
    execvp(argv[optind], &argv[optind]);
    err(EXIT_FAILURE, _("failed to execute %s"), argv[optind]);
  }
}

Project: util-linux
File: su-common.c

static int su_pam_conv(int num_msg, const struct pam_message **msg,
                       struct pam_response **resp, void *appdata_ptr)
{
	if (suppress_pam_info
	    && num_msg == 1
	    && msg
	    && msg[0]->msg_style == PAM_TEXT_INFO)
		return PAM_SUCCESS;
#ifdef HAVE_SECURITY_PAM_MISC_H
	return misc_conv(num_msg, msg, resp, appdata_ptr);
#elif defined(HAVE_SECURITY_OPENPAM_H)
	return openpam_ttyconv(num_msg, msg, resp, appdata_ptr);
#endif
}

Project: util-linux
File: su-common.c

usage (int status)
{
  if (su_mode == RUNUSER_MODE) {
    fputs(USAGE_HEADER, stdout);
    printf (_(" %s [options] -u <user> [[--] <command>]\n"), program_invocation_short_name);
    printf (_(" %s [options] [-] [<user> [<argument>...]]\n"), program_invocation_short_name);
    fputs (_("\n"
    "Run <command> with the effective user ID and group ID of <user>.  If -u is\n"
    "not given, fall back to su(1)-compatible semantics and execute standard shell.\n"
    "The options -c, -f, -l, and -s are mutually exclusive with -u.\n"), stdout);

    fputs(USAGE_OPTIONS, stdout);

    fputs (_(" -u, --user <user>             username\n"), stdout);

  } else {
    fputs(USAGE_HEADER, stdout);
    printf (_(" %s [options] [-] [<user> [<argument>...]]\n"), program_invocation_short_name);
    fputs (_("\n"
    "Change the effective user ID and group ID to that of <user>.\n"
    "A mere - implies -l.  If <user> is not given, root is assumed.\n"), stdout);

    fputs(USAGE_OPTIONS, stdout);
  }

  fputs (_(" -m, -p, --preserve-environment  do not reset environment variables\n"), stdout);
  fputs (_(" -g, --group <group>             specify the primary group\n"), stdout);
  fputs (_(" -G, --supp-group <group>        specify a supplemental group\n\n"), stdout);

  fputs (_(" -, -l, --login                  make the shell a login shell\n"), stdout);
  fputs (_(" -c, --command <command>         pass a single command to the shell with -c\n"), stdout);
  fputs (_(" --session-command <command>     pass a single command to the shell with -c\n"
           "                                   and do not create a new session\n"), stdout);
  fputs (_(" -f, --fast                      pass -f to the shell (for csh or tcsh)\n"), stdout);
  fputs (_(" -s, --shell <shell>             run <shell> if /etc/shells allows it\n"), stdout);

  fputs(USAGE_SEPARATOR, stdout);
  fputs(USAGE_HELP, stdout);
  fputs(USAGE_VERSION, stdout);
  printf(USAGE_MAN_TAIL(su_mode == SU_MODE ? "su(1)" : "runuser(1)"));
  exit (status);
}