2 * Copyright (c) 1989 - 1994, Julianne Frances Haugh
3 * Copyright (c) 1996 - 2000, Marek Michałkiewicz
4 * Copyright (c) 2000 - 2006, Tomasz Kłoczko
5 * Copyright (c) 2007 - 2008, Nicolas François
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. The name of the copyright holders or contributors may not be used to
17 * endorse or promote products derived from this software without
18 * specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
23 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 /* Some parts substantially derived from an ancestor of:
34 su for GNU. Run a shell with substitute user and group IDs.
36 Copyright (C) 1992-2003 Free Software Foundation, Inc.
38 This program is free software; you can redistribute it and/or modify
39 it under the terms of the GNU General Public License as published by
40 the Free Software Foundation; either version 2, or (at your option)
43 This program is distributed in the hope that it will be useful,
44 but WITHOUT ANY WARRANTY; without even the implied warranty of
45 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
46 GNU General Public License for more details.
48 You should have received a copy of the GNU General Public License
49 along with this program; if not, write to the Free Software
50 Foundation, Inc., 51 Franklin Street, Fifth Floor,
51 Boston, MA 02110-1301, USA. */
63 #include <sys/types.h>
64 #include "prototypes.h"
66 #include "exitcodes.h"
73 * Assorted #defines to control su's behavior
78 /* not needed by sulog.c anymore */
79 static char name[BUFSIZ];
80 static char oldname[BUFSIZ];
82 /* If nonzero, change some environment vars to indicate the user su'd to. */
83 static bool change_environment;
86 static pam_handle_t *pamh = NULL;
87 static bool caught = false;
91 extern struct passwd pwent;
94 * External identifiers
97 extern char **newenvp;
98 extern char **environ;
99 extern size_t newenvc;
101 /* local function prototypes */
105 static RETSIGTYPE die (int);
106 static int iswheel (const char *);
109 * die - set or reset termio modes.
111 * die() is called before processing begins. signal() is then called
112 * with die() as the signal handler. If signal later calls die() with a
113 * signal number, the terminal modes are then reset.
115 static RETSIGTYPE die (int killed)
130 static int iswheel (const char *username)
134 grp = getgrnam ("wheel"); /* !USE_PAM, no need for xgetgrnam */
135 if (!grp || !grp->gr_mem)
137 return is_on_list (grp->gr_mem, username);
139 #endif /* !USE_PAM */
141 /* borrowed from GNU sh-utils' "su.c" */
142 static bool restricted_shell (const char *shellstr)
147 while ((line = getusershell ()) != NULL) {
148 if (('#' != *line) && (strcmp (line, shellstr) == 0)) {
157 static void su_failure (const char *tty)
159 sulog (tty, 0, oldname, name); /* log failed attempt */
161 if (getdef_bool ("SYSLOG_SU_ENAB"))
162 SYSLOG (((0 != pwent.pw_uid) ? LOG_INFO : LOG_NOTICE,
164 ('\0' != oldname[0]) ? oldname : "???",
165 ('\0' != name[0]) ? name : "???"));
173 /* Signal handler for parent process later */
174 static void catch_signals (unused int sig)
179 /* This I ripped out of su.c from sh-utils after the Mandrake pam patch
180 * have been applied. Some work was needed to get it integrated into
183 static void run_shell (const char *shellstr, char *args[], bool doshell,
192 if (child == 0) { /* child shell */
194 * PAM_DATA_SILENT is not supported by some modules, and
195 * there is no strong need to clean up the process space's
196 * memory since we will either call exec or exit.
197 pam_end (pamh, PAM_SUCCESS | PAM_DATA_SILENT);
201 (void) shell (shellstr, (char *) args[0], envp);
203 (void) execve (shellstr, (char **) args, envp);
205 exit (errno == ENOENT ? E_CMD_NOTFOUND : E_CMD_NOEXEC);
206 } else if ((pid_t)-1 == child) {
207 (void) fprintf (stderr, "%s: Cannot fork user shell\n", Prog);
208 SYSLOG ((LOG_WARN, "Cannot execute %s", shellstr));
213 sigfillset (&ourset);
214 if (sigprocmask (SIG_BLOCK, &ourset, NULL) != 0) {
215 (void) fprintf (stderr, "%s: signal malfunction\n", Prog);
219 struct sigaction action;
221 action.sa_handler = catch_signals;
222 sigemptyset (&action.sa_mask);
224 sigemptyset (&ourset);
226 if ( (sigaddset (&ourset, SIGTERM) != 0)
227 || (sigaddset (&ourset, SIGALRM) != 0)
228 || (sigaction (SIGTERM, &action, NULL) != 0)
229 || (sigprocmask (SIG_UNBLOCK, &ourset, NULL) != 0)
232 "%s: signal masking malfunction\n", Prog);
241 pid = waitpid (-1, &status, WUNTRACED);
243 if (((pid_t)-1 != pid) && (0 != WIFSTOPPED (status))) {
244 /* The child (shell) was suspended.
246 kill (getpid (), WSTOPSIG(status));
247 /* wake child when resumed */
250 } while (0 != WIFSTOPPED (status));
254 fprintf (stderr, "\nSession terminated, killing shell...");
255 kill (child, SIGTERM);
258 ret = pam_close_session (pamh, 0);
259 if (PAM_SUCCESS != ret) {
260 SYSLOG ((LOG_ERR, "pam_close_session: %s",
261 pam_strerror (pamh, ret)));
262 fprintf (stderr, _("%s: %s\n"), Prog, pam_strerror (pamh, ret));
263 (void) pam_end (pamh, ret);
267 ret = pam_end (pamh, PAM_SUCCESS);
271 kill (child, SIGKILL);
272 fprintf (stderr, " ...killed.\n");
276 exit ((0 != WIFEXITED (status)) ? WEXITSTATUS (status)
277 : WTERMSIG (status) + 128);
282 * usage - print command line syntax and exit
284 static void usage (void)
286 fputs (_("Usage: su [options] [LOGIN]\n"
289 " -c, --command COMMAND pass COMMAND to the invoked shell\n"
290 " -h, --help display this help message and exit\n"
291 " -, -l, --login make the shell a login shell\n"
293 " --preserve-environment do not reset environment variables, and\n"
294 " keep the same shell\n"
295 " -s, --shell SHELL use SHELL instead of the default in passwd\n"
301 * su - switch user id
303 * su changes the user's ids to the values for the specified user. if
304 * no new user name is specified, "root" is used by default.
306 * Any additional arguments are passed to the user's shell. In
307 * particular, the argument "-c" will cause the next argument to be
308 * interpreted as a command by the common shell programs.
310 int main (int argc, char **argv)
313 const char *tty = NULL; /* Name of tty SU is run from */
314 bool doshell = false;
315 bool fakelogin = false;
318 struct passwd *pw = NULL;
319 char **envp = environ;
320 char *shellstr = NULL;
321 char *command = NULL;
329 RETSIGTYPE (*oldsig) (int);
332 struct spwd *spwd = 0;
337 #endif /* !USE_PAM */
341 (void) setlocale (LC_ALL, "");
342 (void) bindtextdomain (PACKAGE, LOCALEDIR);
343 (void) textdomain (PACKAGE);
345 change_environment = true;
348 * Get the program name. The program name is used as a prefix to
349 * most error messages.
351 Prog = Basename (argv[0]);
356 * Process the command line arguments.
361 * Parse the command line options.
363 int option_index = 0;
365 static struct option long_options[] = {
366 {"command", required_argument, NULL, 'c'},
367 {"help", no_argument, NULL, 'h'},
368 {"login", no_argument, NULL, 'l'},
369 {"preserve-environment", no_argument, NULL, 'p'},
370 {"shell", required_argument, NULL, 's'},
371 {NULL, 0, NULL, '\0'}
375 getopt_long (argc, argv, "c:hlmps:", long_options,
376 &option_index)) != -1) {
389 /* This will only have an effect if the target
390 * user do not have a restricted shell, or if
391 * su is called by root.
393 change_environment = false;
399 usage (); /* NOT REACHED */
403 if ((optind < argc) && (strcmp (argv[optind], "-") == 0)) {
407 && (strcmp (argv[optind], "--") == 0)) {
416 amroot = (my_uid == 0);
419 * Get the tty name. Entries will be logged indicating that the user
420 * tried to change to the named new user from the current terminal.
423 if ((isatty (0) != 0) && (NULL != cp)) {
424 if (strncmp (cp, "/dev/", 5) == 0) {
430 is_console = console (tty);
434 * Be more paranoid, like su from SimplePAMApps. --marekm
438 _("%s: must be run from a terminal\n"), Prog);
445 * The next argument must be either a user ID, or some flag to a
446 * subshell. Pretty sticky since you can't have an argument which
447 * doesn't start with a "-" unless you specify the new user name.
448 * Any remaining arguments will be passed to the user's login shell.
450 if ((optind < argc) && ('-' != argv[optind][0])) {
451 STRFCPY (name, argv[optind++]); /* use this login id */
452 if ((optind < argc) && (strcmp (argv[optind], "--") == 0)) {
456 if ('\0' == name[0]) { /* use default user ID */
457 (void) strcpy (name, "root");
460 doshell = (argc == optind); /* any arguments remaining? */
461 if (NULL != command) {
466 * Get the user's real name. The current UID is used to determine
467 * who has executed su. That user ID must exist.
469 pw = get_my_pwent ();
471 SYSLOG ((LOG_CRIT, "Unknown UID: %u", my_uid));
474 STRFCPY (oldname, pw->pw_name);
479 * Sort out the password of user calling su, in case needed later
482 spwd = getspnam (oldname); /* !USE_PAM, no need for xgetspnam */
484 pw->pw_passwd = spwd->sp_pwdp;
486 oldpass = xstrdup (pw->pw_passwd);
487 #endif /* SU_ACCESS */
490 ret = pam_start ("su", name, &conv, &pamh);
491 if (PAM_SUCCESS != ret) {
492 SYSLOG ((LOG_ERR, "pam_start: error %d", ret);
493 fprintf (stderr, _("%s: pam_start: error %d\n"),
498 ret = pam_set_item (pamh, PAM_TTY, (const void *) tty);
499 if (PAM_SUCCESS == ret) {
500 ret = pam_set_item (pamh, PAM_RUSER, (const void *) oldname);
502 if (PAM_SUCCESS != ret) {
503 SYSLOG ((LOG_ERR, "pam_set_item: %s",
504 pam_strerror (pamh, ret)));
505 fprintf (stderr, _("%s: %s\n"), Prog, pam_strerror (pamh, ret));
513 * This is the common point for validating a user whose name is
514 * known. It will be reached either by normal processing, or if the
515 * user is to be logged into a subsystem root.
517 * The password file entries for the user is gotten and the account
520 pw = xgetpwnam (name);
522 (void) fprintf (stderr, _("Unknown id: %s\n"), name);
528 if (strcmp (pw->pw_passwd, SHADOW_PASSWD_STRING) == 0) {
529 spwd = getspnam (name); /* !USE_PAM, no need for xgetspnam */
531 pw->pw_passwd = spwd->sp_pwdp;
534 #endif /* !USE_PAM */
537 /* If su is not called by root, and the target user has a restricted
538 * shell, the environment must be changed.
540 change_environment |= (restricted_shell (pwent.pw_shell) && !amroot);
543 * If a new login is being set up, the old environment will be
544 * ignored and a new one created later on.
545 * (note: in the case of a subsystem, the shell will be restricted,
546 * and this won't be executed on the first pass)
548 if (fakelogin && change_environment) {
550 * The terminal type will be left alone if it is present in
551 * the environment already.
553 cp = getenv ("TERM");
558 cp = getdef_str ("ENV_TZ");
560 addenv (('/' == *cp) ? tz (cp) : cp, NULL);
564 * The clock frequency will be reset to the login value if required
566 cp = getdef_str ("ENV_HZ");
568 addenv (cp, NULL); /* set the default $HZ, if one */
572 * Also leave DISPLAY and XAUTHORITY if present, else
573 * pam_xauth will not work.
575 cp = getenv ("DISPLAY");
577 addenv ("DISPLAY", cp);
579 cp = getenv ("XAUTHORITY");
581 addenv ("XAUTHORITY", cp);
583 #endif /* !USE_PAM */
585 while (NULL != *envp) {
586 addenv (*envp, NULL);
593 * BSD systems only allow "wheel" to SU to root. USG systems don't,
594 * so we make this a configurable option.
597 /* The original Shadow 3.3.2 did this differently. Do it like BSD:
599 * - check for UID 0 instead of name "root" - there are systems with
600 * several root accounts under different names,
602 * - check the contents of /etc/group instead of the current group
603 * set (you must be listed as a member, GID 0 is not sufficient).
605 * In addition to this traditional feature, we now have complete su
606 * access control (allow, deny, no password, own password). Thanks
607 * to Chris Evans <lady0110@sable.ox.ac.uk>.
611 if ( (0 == pwent.pw_uid)
612 && getdef_bool ("SU_WHEEL_ONLY")
613 && !iswheel (oldname)) {
615 _("You are not authorized to su %s\n"), name);
619 switch (check_su_auth (oldname, name)) {
620 case 0: /* normal su, require target user's password */
622 case 1: /* require no password */
623 pwent.pw_passwd = ""; /* XXX warning: const */
625 case 2: /* require own password */
626 puts (_("(Enter your own password)"));
627 pwent.pw_passwd = oldpass;
629 default: /* access denied (-1) or unexpected value */
631 _("You are not authorized to su %s\n"), name);
634 #endif /* SU_ACCESS */
636 #endif /* !USE_PAM */
638 /* If the user do not want to change the environment,
639 * use the current SHELL.
640 * (unless another shell is required by the command line)
642 if ((NULL == shellstr) && !change_environment) {
643 shellstr = getenv ("SHELL");
645 /* For users with non null UID, if this user has a restricted
646 * shell, the shell must be the one specified in /etc/passwd
648 if ( (NULL != shellstr)
650 && restricted_shell (pwent.pw_shell)) {
653 /* If the shell is not set at this time, use the shell specified
656 if (NULL == shellstr) {
657 shellstr = (char *) strdup (pwent.pw_shell);
661 * Set the default shell.
663 if ((NULL == shellstr) || ('\0' == shellstr[0])) {
664 shellstr = "/bin/sh";
667 (void) signal (SIGINT, SIG_IGN);
668 (void) signal (SIGQUIT, SIG_IGN);
670 ret = pam_authenticate (pamh, 0);
671 if (PAM_SUCCESS != ret) {
672 SYSLOG ((LOG_ERR, "pam_authenticate: %s",
673 pam_strerror (pamh, ret)));
674 fprintf (stderr, _("%s: %s\n"), Prog, pam_strerror (pamh, ret));
675 (void) pam_end (pamh, ret);
679 ret = pam_acct_mgmt (pamh, 0);
680 if (PAM_SUCCESS != ret) {
682 fprintf (stderr, _("%s: %s\n(Ignored)\n"), Prog,
683 pam_strerror (pamh, ret));
684 } else if (PAM_NEW_AUTHTOK_REQD == ret) {
685 ret = pam_chauthtok (pamh, PAM_CHANGE_EXPIRED_AUTHTOK);
686 if (PAM_SUCCESS != ret) {
687 SYSLOG ((LOG_ERR, "pam_chauthtok: %s",
688 pam_strerror (pamh, ret)));
689 fprintf (stderr, _("%s: %s\n"), Prog,
690 pam_strerror (pamh, ret));
691 (void) pam_end (pamh, ret);
695 SYSLOG ((LOG_ERR, "pam_acct_mgmt: %s",
696 pam_strerror (pamh, ret)));
697 fprintf (stderr, _("%s: %s\n"), Prog,
698 pam_strerror (pamh, ret));
699 (void) pam_end (pamh, ret);
705 * Set up a signal handler in case the user types QUIT.
708 (void) oldsig = signal (SIGQUIT, die);
711 * See if the system defined authentication method is being used.
712 * The first character of an administrator defined method is an '@'
715 if (!amroot && pw_auth (pwent.pw_passwd, name, PW_SU, (char *) 0)) {
716 SYSLOG ((pwent.pw_uid ? LOG_NOTICE : LOG_WARN,
717 "Authentication failed for %s", name));
720 (void) signal (SIGQUIT, oldsig);
723 * Check to see if the account is expired. root gets to ignore any
724 * expired accounts, but normal users can't become a user with an
729 spwd = pwd_to_spwd (&pwent);
732 if (expire (&pwent, spwd)) {
733 /* !USE_PAM, no need for xgetpwnam */
734 struct passwd *pwd = getpwnam (name);
736 /* !USE_PAM, no need for xgetspnam */
737 spwd = getspnam (name);
745 * Check to see if the account permits "su". root gets to ignore any
746 * restricted accounts, but normal users can't become a user if
747 * there is a "SU" entry in the /etc/porttime file denying access to
751 if (!isttytime (pwent.pw_name, "SU", time ((time_t *) 0))) {
752 SYSLOG (((0 != pwent.pw_uid) ? LOG_WARN : LOG_CRIT,
753 "SU by %s to restricted account %s",
758 #endif /* !USE_PAM */
760 (void) signal (SIGINT, SIG_DFL);
761 (void) signal (SIGQUIT, SIG_DFL);
763 cp = getdef_str ((pwent.pw_uid == 0) ? "ENV_SUPATH" : "ENV_PATH");
765 addenv ("PATH=/bin:/usr/bin", NULL);
766 } else if (strchr (cp, '=') != NULL) {
772 if (getenv ("IFS") != NULL) { /* don't export user IFS ... */
773 addenv ("IFS= \t\n", NULL); /* ... instead, set a safe IFS */
777 * Even if --shell is specified, the subsystem login test is based on
778 * the shell specified in /etc/passwd (not the one specified with
779 * --shell, which will be the one executed in the chroot later).
781 if ('*' == pwent.pw_shell[0]) { /* subsystem root required */
782 pwent.pw_shell++; /* skip the '*' */
783 subsystem (&pwent); /* figure out what to execute */
789 sulog (tty, true, oldname, name); /* save SU information */
793 if (getdef_bool ("SYSLOG_SU_ENAB")) {
794 SYSLOG ((LOG_INFO, "+ %s %s:%s", tty,
795 ('\0' != oldname[0]) ? oldname : "???",
796 ('\0' != name[0]) ? name : "???"));
801 /* set primary group id and supplementary groups */
802 if (setup_groups (&pwent) != 0) {
803 pam_end (pamh, PAM_ABORT);
808 * pam_setcred() may do things like resource limits, console groups,
809 * and much more, depending on the configured modules
811 ret = pam_setcred (pamh, PAM_ESTABLISH_CRED);
812 if (PAM_SUCCESS != ret) {
813 SYSLOG ((LOG_ERR, "pam_setcred: %s", pam_strerror (pamh, ret)));
814 fprintf (stderr, _("%s: %s\n"), Prog, pam_strerror (pamh, ret));
815 (void) pam_end (pamh, ret);
819 ret = pam_open_session (pamh, 0);
820 if (PAM_SUCCESS != ret) {
821 SYSLOG ((LOG_ERR, "pam_open_session: %s",
822 pam_strerror (pamh, ret)));
823 fprintf (stderr, _("%s: %s\n"), Prog, pam_strerror (pamh, ret));
824 pam_setcred (pamh, PAM_DELETE_CRED);
825 (void) pam_end (pamh, ret);
829 if (change_environment) {
830 /* we need to setup the environment *after* pam_open_session(),
831 * else the UID is changed before stuff like pam_xauth could
832 * run, and we cannot access /etc/shadow and co
834 environ = newenvp; /* make new environment active */
836 /* update environment with all pam set variables */
837 envcp = pam_getenvlist (pamh);
839 while (NULL != *envcp) {
840 addenv (*envcp, NULL);
846 /* become the new user */
847 if (change_uid (&pwent) != 0) {
848 pam_close_session (pamh, 0);
849 pam_setcred (pamh, PAM_DELETE_CRED);
850 (void) pam_end (pamh, PAM_ABORT);
854 environ = newenvp; /* make new environment active */
856 /* no limits if su from root (unless su must fake login's behavior) */
857 if (!amroot || fakelogin) {
858 setup_limits (&pwent);
861 if (setup_uid_gid (&pwent, is_console) != 0) {
864 #endif /* !USE_PAM */
866 if (change_environment) {
868 pwent.pw_shell = shellstr;
871 addenv ("HOME", pwent.pw_dir);
872 addenv ("USER", pwent.pw_name);
873 addenv ("LOGNAME", pwent.pw_name);
874 addenv ("SHELL", shellstr);
879 * This is a workaround for Linux libc bug/feature (?) - the
880 * /dev/log file descriptor is open without the close-on-exec flag
881 * and used to be passed to the new shell. There is "fcntl(LogFile,
882 * F_SETFD, 1)" in libc/misc/syslog.c, but it is commented out (at
883 * least in 5.4.33). Why? --marekm
888 * See if the user has extra arguments on the command line. In that
889 * case they will be provided to the new user's shell as arguments.
894 cp = getdef_str ("SU_NAME");
896 cp = Basename (shellstr);
899 arg0 = xmalloc (strlen (cp) + 2);
901 strcpy (arg0 + 1, cp);
904 cp = Basename (shellstr);
908 /* Position argv to the remaining arguments */
910 if (NULL != command) {
916 * Use the shell and create an argv
917 * with the rest of the command line included.
921 (void) execve (shellstr, &argv[-1], environ);
923 (void) fputs (_("No shell\n"), stderr);
924 SYSLOG ((LOG_WARN, "Cannot execute %s", shellstr));
926 exit ((ENOENT == err) ? E_CMD_NOTFOUND : E_CMD_NOEXEC);
928 run_shell (shellstr, &argv[-1], false, environ); /* no return */
932 err = shell (shellstr, cp, environ);
933 exit ((ENOENT == err) ? E_CMD_NOTFOUND : E_CMD_NOEXEC);
935 run_shell (shellstr, &cp, true, environ);