2 * Copyright 1989 - 1994, Julianne Frances Haugh
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. Neither the name of Julianne F. Haugh nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY JULIE HAUGH AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL JULIE HAUGH OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 /* Some parts substantially derived from an ancestor of: */
30 /* su for GNU. Run a shell with substitute user and group IDs.
31 Copyright (C) 1992-2003 Free Software Foundation, Inc.
33 This program is free software; you can redistribute it and/or modify
34 it under the terms of the GNU General Public License as published by
35 the Free Software Foundation; either version 2, or (at your option)
38 This program is distributed in the hope that it will be useful,
39 but WITHOUT ANY WARRANTY; without even the implied warranty of
40 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
41 GNU General Public License for more details.
43 You should have received a copy of the GNU General Public License
44 along with this program; if not, write to the Free Software Foundation,
45 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
57 #include <sys/types.h>
58 #include "prototypes.h"
60 #include "exitcodes.h"
67 * Assorted #defines to control su's behavior
72 /* not needed by sulog.c anymore */
73 static char name[BUFSIZ];
74 static char oldname[BUFSIZ];
76 /* If nonzero, change some environment vars to indicate the user su'd to. */
77 static int change_environment;
80 static pam_handle_t *pamh = NULL;
81 static int caught = 0;
85 extern struct passwd pwent;
88 * External identifiers
91 extern char **newenvp;
92 extern char **environ;
93 extern size_t newenvc;
95 /* local function prototypes */
99 static RETSIGTYPE die (int);
100 static int iswheel (const char *);
103 * die - set or reset termio modes.
105 * die() is called before processing begins. signal() is then called
106 * with die() as the signal handler. If signal later calls die() with a
107 * signal number, the terminal modes are then reset.
109 static RETSIGTYPE die (int killed)
124 static int iswheel (const char *username)
128 grp = getgrnam ("wheel");;
129 if (!grp || !grp->gr_mem)
131 return is_on_list (grp->gr_mem, username);
133 #endif /* !USE_PAM */
135 /* borrowed from GNU sh-utils' "su.c" */
136 static int restricted_shell (const char *shellstr)
141 while ((line = getusershell ()) != NULL) {
142 if (*line != '#' && strcmp (line, shellstr) == 0) {
151 static void su_failure (const char *tty)
153 sulog (tty, 0, oldname, name); /* log failed attempt */
155 if (getdef_bool ("SYSLOG_SU_ENAB"))
156 SYSLOG ((pwent.pw_uid ? LOG_INFO : LOG_NOTICE,
158 oldname[0] ? oldname : "???", name[0] ? name : "???"));
166 /* Signal handler for parent process later */
167 static void catch_signals (int sig)
172 /* This I ripped out of su.c from sh-utils after the Mandrake pam patch
173 * have been applied. Some work was needed to get it integrated into
176 static void run_shell (const char *shellstr, char *args[], int doshell,
185 if (child == 0) { /* child shell */
186 pam_end (pamh, PAM_SUCCESS);
189 (void) shell (shellstr, (char *) args[0], envp);
191 (void) execve (shellstr, (char **) args, envp);
192 exit (errno == ENOENT ? E_CMD_NOTFOUND : E_CMD_NOEXEC);
193 } else if (child == -1) {
194 (void) fprintf (stderr, "%s: Cannot fork user shell\n", Prog);
195 SYSLOG ((LOG_WARN, "Cannot execute %s", shellstr));
200 sigfillset (&ourset);
201 if (sigprocmask (SIG_BLOCK, &ourset, NULL)) {
202 (void) fprintf (stderr, "%s: signal malfunction\n", Prog);
206 struct sigaction action;
208 action.sa_handler = catch_signals;
209 sigemptyset (&action.sa_mask);
211 sigemptyset (&ourset);
213 if (sigaddset (&ourset, SIGTERM)
214 || sigaddset (&ourset, SIGALRM)
215 || sigaction (SIGTERM, &action, NULL)
216 || sigprocmask (SIG_UNBLOCK, &ourset, NULL)
219 "%s: signal masking malfunction\n", Prog);
228 pid = waitpid (-1, &status, WUNTRACED);
230 if (WIFSTOPPED (status)) {
231 kill (getpid (), SIGSTOP);
232 /* once we get here, we must have resumed */
235 } while (WIFSTOPPED (status));
239 fprintf (stderr, "\nSession terminated, killing shell...");
240 kill (child, SIGTERM);
243 ret = pam_close_session (pamh, 0);
244 if (ret != PAM_SUCCESS) {
245 SYSLOG ((LOG_ERR, "pam_close_session: %s",
246 pam_strerror (pamh, ret)));
247 fprintf (stderr, _("%s: %s\n"), Prog, pam_strerror (pamh, ret));
252 ret = pam_end (pamh, PAM_SUCCESS);
256 kill (child, SIGKILL);
257 fprintf (stderr, " ...killed.\n");
261 exit (WIFEXITED (status)
262 ? WEXITSTATUS (status)
263 : WTERMSIG (status) + 128);
268 * usage - print command line syntax and exit
270 static void usage (void)
272 fprintf (stderr, _("Usage: su [options] [LOGIN]\n"
275 " -c, --command COMMAND pass COMMAND to the invoked shell\n"
276 " -h, --help display this help message and exit\n"
277 " -, -l, --login make the shell a login shell\n"
279 " --preserve-environment do not reset environment variables, and keep\n"
281 " -s, --shell SHELL use SHELL instead of the default in passwd\n"
287 * su - switch user id
289 * su changes the user's ids to the values for the specified user. if
290 * no new user name is specified, "root" is used by default.
292 * Any additional arguments are passed to the user's shell. In
293 * particular, the argument "-c" will cause the next argument to be
294 * interpreted as a command by the common shell programs.
296 int main (int argc, char **argv)
299 const char *tty = 0; /* Name of tty SU is run from */
304 struct passwd *pw = 0;
305 char **envp = environ;
306 char *shellstr = 0, *command = 0;
314 RETSIGTYPE (*oldsig) ();
317 struct spwd *spwd = 0;
322 #endif /* !USE_PAM */
326 setlocale (LC_ALL, "");
327 bindtextdomain (PACKAGE, LOCALEDIR);
328 textdomain (PACKAGE);
330 change_environment = 1;
333 * Get the program name. The program name is used as a prefix to
334 * most error messages.
336 Prog = Basename (argv[0]);
341 * Process the command line arguments.
346 * Parse the command line options.
348 int option_index = 0;
350 static struct option long_options[] = {
351 {"command", required_argument, NULL, 'c'},
352 {"help", no_argument, NULL, 'h'},
353 {"login", no_argument, NULL, 'l'},
354 {"preserve-environment", no_argument, NULL, 'p'},
355 {"shell", required_argument, NULL, 's'},
356 {NULL, 0, NULL, '\0'}
360 getopt_long (argc, argv, "-c:hlmps:", long_options,
361 &option_index)) != -1) {
364 /* this is not an su option */
365 /* The next arguments are either '-', the
366 * target name, or arguments to be passed
369 /* rewind the (not yet handled) option */
372 break; /* NOT REACHED */
384 /* This will only have an effect if the target
385 * user do not have a restricted shell, or if
386 * su is called by root.
388 change_environment = 0;
394 usage (); /* NOT REACHED */
398 if (optind < argc && !strcmp (argv[optind], "-")) {
401 if (optind < argc && !strcmp (argv[optind], "--"))
409 amroot = (my_uid == 0);
412 * Get the tty name. Entries will be logged indicating that the user
413 * tried to change to the named new user from the current terminal.
415 if (isatty (0) && (cp = ttyname (0))) {
416 if (strncmp (cp, "/dev/", 5) == 0)
421 is_console = console (tty);
425 * Be more paranoid, like su from SimplePAMApps. --marekm
429 _("%s: must be run from a terminal\n"), Prog);
436 * The next argument must be either a user ID, or some flag to a
437 * subshell. Pretty sticky since you can't have an argument which
438 * doesn't start with a "-" unless you specify the new user name.
439 * Any remaining arguments will be passed to the user's login shell.
441 if (optind < argc && argv[optind][0] != '-') {
442 STRFCPY (name, argv[optind++]); /* use this login id */
443 if (optind < argc && !strcmp (argv[optind], "--"))
446 if (!name[0]) /* use default user ID */
447 (void) strcpy (name, "root");
449 doshell = argc == optind; /* any arguments remaining? */
454 * Get the user's real name. The current UID is used to determine
455 * who has executed su. That user ID must exist.
457 pw = get_my_pwent ();
459 SYSLOG ((LOG_CRIT, "Unknown UID: %u", my_uid));
462 STRFCPY (oldname, pw->pw_name);
467 * Sort out the password of user calling su, in case needed later
470 if ((spwd = getspnam (oldname)))
471 pw->pw_passwd = spwd->sp_pwdp;
472 oldpass = xstrdup (pw->pw_passwd);
473 #endif /* SU_ACCESS */
476 ret = pam_start ("su", name, &conv, &pamh);
477 if (ret != PAM_SUCCESS) {
478 SYSLOG ((LOG_ERR, "pam_start: error %d", ret);
479 fprintf (stderr, _("%s: pam_start: error %d\n"),
484 ret = pam_set_item (pamh, PAM_TTY, (const void *) tty);
485 if (ret == PAM_SUCCESS)
486 ret = pam_set_item (pamh, PAM_RUSER, (const void *) oldname);
487 if (ret != PAM_SUCCESS) {
488 SYSLOG ((LOG_ERR, "pam_set_item: %s",
489 pam_strerror (pamh, ret)));
490 fprintf (stderr, _("%s: %s\n"), Prog, pam_strerror (pamh, ret));
498 * This is the common point for validating a user whose name is
499 * known. It will be reached either by normal processing, or if the
500 * user is to be logged into a subsystem root.
502 * The password file entries for the user is gotten and the account
505 if (!(pw = getpwnam (name))) {
506 (void) fprintf (stderr, _("Unknown id: %s\n"), name);
512 if (strcmp (pw->pw_passwd, SHADOW_PASSWD_STRING) == 0
513 && (spwd = getspnam (name)))
514 pw->pw_passwd = spwd->sp_pwdp;
515 #endif /* !USE_PAM */
518 /* If su is not called by root, and the target user has a restricted
519 * shell, the environment must be changed.
521 change_environment |= (restricted_shell (pwent.pw_shell) && !amroot);
524 * If a new login is being set up, the old environment will be
525 * ignored and a new one created later on.
526 * (note: in the case of a subsystem, the shell will be restricted,
527 * and this won't be executed on the first pass)
529 if (fakelogin && change_environment) {
531 * The terminal type will be left alone if it is present in
532 * the environment already.
534 if ((cp = getenv ("TERM")))
537 if ((cp = getdef_str ("ENV_TZ")))
538 addenv (*cp == '/' ? tz (cp) : cp, NULL);
541 * The clock frequency will be reset to the login value if required
543 if ((cp = getdef_str ("ENV_HZ")))
544 addenv (cp, NULL); /* set the default $HZ, if one */
547 * Also leave DISPLAY and XAUTHORITY if present, else
548 * pam_xauth will not work.
550 if ((cp = getenv ("DISPLAY")))
551 addenv ("DISPLAY", cp);
552 if ((cp = getenv ("XAUTHORITY")))
553 addenv ("XAUTHORITY", cp);
554 #endif /* !USE_PAM */
557 addenv (*envp++, NULL);
562 * BSD systems only allow "wheel" to SU to root. USG systems don't,
563 * so we make this a configurable option.
566 /* The original Shadow 3.3.2 did this differently. Do it like BSD:
568 * - check for UID 0 instead of name "root" - there are systems with
569 * several root accounts under different names,
571 * - check the contents of /etc/group instead of the current group
572 * set (you must be listed as a member, GID 0 is not sufficient).
574 * In addition to this traditional feature, we now have complete su
575 * access control (allow, deny, no password, own password). Thanks
576 * to Chris Evans <lady0110@sable.ox.ac.uk>.
580 if (pwent.pw_uid == 0 && getdef_bool ("SU_WHEEL_ONLY")
581 && !iswheel (oldname)) {
583 _("You are not authorized to su %s\n"), name);
587 switch (check_su_auth (oldname, name)) {
588 case 0: /* normal su, require target user's password */
590 case 1: /* require no password */
591 pwent.pw_passwd = ""; /* XXX warning: const */
593 case 2: /* require own password */
594 puts (_("(Enter your own password)"));
595 pwent.pw_passwd = oldpass;
597 default: /* access denied (-1) or unexpected value */
599 _("You are not authorized to su %s\n"), name);
602 #endif /* SU_ACCESS */
604 #endif /* !USE_PAM */
606 /* If the user do not want to change the environment,
607 * use the current SHELL.
608 * (unless another shell is required by the command line)
610 if (shellstr == NULL && change_environment == 0)
611 shellstr = getenv ("SHELL");
612 /* For users with non null UID, if this user has a restricted
613 * shell, the shell must be the one specified in /etc/passwd
615 if (shellstr != NULL && !amroot && restricted_shell (pwent.pw_shell))
617 /* If the shell is not set at this time, use the shell specified
620 if (shellstr == NULL)
621 shellstr = (char *) strdup (pwent.pw_shell);
624 * Set the default shell.
626 if (shellstr == NULL || shellstr[0] == '\0')
627 shellstr = "/bin/sh";
629 signal (SIGINT, SIG_IGN);
630 signal (SIGQUIT, SIG_IGN);
632 ret = pam_authenticate (pamh, 0);
633 if (ret != PAM_SUCCESS) {
634 SYSLOG ((LOG_ERR, "pam_authenticate: %s",
635 pam_strerror (pamh, ret)));
636 fprintf (stderr, _("%s: %s\n"), Prog, pam_strerror (pamh, ret));
641 ret = pam_acct_mgmt (pamh, 0);
642 if (ret != PAM_SUCCESS) {
644 fprintf (stderr, _("%s: %s\n(Ignored)\n"), Prog,
645 pam_strerror (pamh, ret));
646 } else if (ret == PAM_NEW_AUTHTOK_REQD) {
647 ret = pam_chauthtok (pamh, PAM_CHANGE_EXPIRED_AUTHTOK);
648 if (ret != PAM_SUCCESS) {
649 SYSLOG ((LOG_ERR, "pam_chauthtok: %s",
650 pam_strerror (pamh, ret)));
651 fprintf (stderr, _("%s: %s\n"), Prog,
652 pam_strerror (pamh, ret));
657 SYSLOG ((LOG_ERR, "pam_acct_mgmt: %s",
658 pam_strerror (pamh, ret)));
659 fprintf (stderr, _("%s: %s\n"), Prog,
660 pam_strerror (pamh, ret));
667 * Set up a signal handler in case the user types QUIT.
670 oldsig = signal (SIGQUIT, die);
673 * See if the system defined authentication method is being used.
674 * The first character of an administrator defined method is an '@'
677 if (!amroot && pw_auth (pwent.pw_passwd, name, PW_SU, (char *) 0)) {
678 SYSLOG ((pwent.pw_uid ? LOG_NOTICE : LOG_WARN,
679 "Authentication failed for %s", name));
682 signal (SIGQUIT, oldsig);
685 * Check to see if the account is expired. root gets to ignore any
686 * expired accounts, but normal users can't become a user with an
691 spwd = pwd_to_spwd (&pwent);
693 if (expire (&pwent, spwd)) {
694 struct passwd *pwd = getpwnam (name);
696 spwd = getspnam (name);
703 * Check to see if the account permits "su". root gets to ignore any
704 * restricted accounts, but normal users can't become a user if
705 * there is a "SU" entry in the /etc/porttime file denying access to
709 if (!isttytime (pwent.pw_name, "SU", time ((time_t *) 0))) {
710 SYSLOG ((pwent.pw_uid ? LOG_WARN : LOG_CRIT,
711 "SU by %s to restricted account %s",
716 #endif /* !USE_PAM */
718 signal (SIGINT, SIG_DFL);
719 signal (SIGQUIT, SIG_DFL);
721 cp = getdef_str ((pwent.pw_uid == 0) ? "ENV_SUPATH" : "ENV_PATH");
723 addenv ("PATH=/bin:/usr/bin", NULL);
724 } else if (strchr (cp, '=')) {
730 if (getenv ("IFS")) /* don't export user IFS ... */
731 addenv ("IFS= \t\n", NULL); /* ... instead, set a safe IFS */
734 * Even if --shell is specified, the subsystem login test is based on
735 * the shell specified in /etc/passwd (not the one specified with
736 * --shell, which will be the one executed in the chroot later).
738 if (pwent.pw_shell[0] == '*') { /* subsystem root required */
739 pwent.pw_shell++; /* skip the '*' */
740 subsystem (&pwent); /* figure out what to execute */
746 sulog (tty, 1, oldname, name); /* save SU information */
750 if (getdef_bool ("SYSLOG_SU_ENAB"))
751 SYSLOG ((LOG_INFO, "+ %s %s:%s", tty,
752 oldname[0] ? oldname : "???", name[0] ? name : "???"));
756 /* set primary group id and supplementary groups */
757 if (setup_groups (&pwent)) {
758 pam_end (pamh, PAM_ABORT);
763 * pam_setcred() may do things like resource limits, console groups,
764 * and much more, depending on the configured modules
766 ret = pam_setcred (pamh, PAM_ESTABLISH_CRED);
767 if (ret != PAM_SUCCESS) {
768 SYSLOG ((LOG_ERR, "pam_setcred: %s", pam_strerror (pamh, ret)));
769 fprintf (stderr, _("%s: %s\n"), Prog, pam_strerror (pamh, ret));
774 ret = pam_open_session (pamh, 0);
775 if (ret != PAM_SUCCESS) {
776 SYSLOG ((LOG_ERR, "pam_open_session: %s",
777 pam_strerror (pamh, ret)));
778 fprintf (stderr, _("%s: %s\n"), Prog, pam_strerror (pamh, ret));
779 pam_setcred (pamh, PAM_DELETE_CRED);
784 if (change_environment) {
785 /* we need to setup the environment *after* pam_open_session(),
786 * else the UID is changed before stuff like pam_xauth could
787 * run, and we cannot access /etc/shadow and co
789 environ = newenvp; /* make new environment active */
791 /* update environment with all pam set variables */
792 envcp = pam_getenvlist (pamh);
795 addenv (*envcp, NULL);
801 /* become the new user */
802 if (change_uid (&pwent)) {
803 pam_close_session (pamh, 0);
804 pam_setcred (pamh, PAM_DELETE_CRED);
805 pam_end (pamh, PAM_ABORT);
809 environ = newenvp; /* make new environment active */
811 /* no limits if su from root (unless su must fake login's behavior) */
812 if (!amroot || fakelogin)
813 setup_limits (&pwent);
815 if (setup_uid_gid (&pwent, is_console))
817 #endif /* !USE_PAM */
819 if (change_environment) {
821 pwent.pw_shell = shellstr;
824 addenv ("HOME", pwent.pw_dir);
825 addenv ("USER", pwent.pw_name);
826 addenv ("LOGNAME", pwent.pw_name);
827 addenv ("SHELL", shellstr);
832 * This is a workaround for Linux libc bug/feature (?) - the
833 * /dev/log file descriptor is open without the close-on-exec flag
834 * and used to be passed to the new shell. There is "fcntl(LogFile,
835 * F_SETFD, 1)" in libc/misc/syslog.c, but it is commented out (at
836 * least in 5.4.33). Why? --marekm
841 * See if the user has extra arguments on the command line. In that
842 * case they will be provided to the new user's shell as arguments.
847 cp = getdef_str ("SU_NAME");
849 cp = Basename (shellstr);
851 arg0 = xmalloc (strlen (cp) + 2);
853 strcpy (arg0 + 1, cp);
856 cp = Basename (shellstr);
859 /* Position argv to the remaining arguments */
867 * Use the shell and create an argv
868 * with the rest of the command line included.
872 (void) execve (shellstr, &argv[-1], environ);
874 (void) fprintf (stderr, _("No shell\n"));
875 SYSLOG ((LOG_WARN, "Cannot execute %s", shellstr));
877 exit (err == ENOENT ? E_CMD_NOTFOUND : E_CMD_NOEXEC);
879 run_shell (shellstr, &argv[-1], 0, environ); /* no return */
883 err = shell (shellstr, cp, environ);
884 exit (err == ENOENT ? E_CMD_NOTFOUND : E_CMD_NOEXEC);
886 run_shell (shellstr, &cp, 1, environ);