]> granicus.if.org Git - shadow/blob - src/su.c
9e011d9674bf947867b352a35dd09d1a6f8e5b5e
[shadow] / src / su.c
1 /*
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
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
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.
19  *
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.
31  */
32
33 /* Some parts substantially derived from an ancestor of:
34    su for GNU.  Run a shell with substitute user and group IDs.
35
36    Copyright (C) 1992-2003 Free Software Foundation, Inc.
37
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)
41    any later version.
42
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.
47
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.  */
52
53
54 #include <config.h>
55
56 #ident "$Id$"
57
58 #include <getopt.h>
59 #include <grp.h>
60 #include <pwd.h>
61 #include <signal.h>
62 #include <stdio.h>
63 #include <sys/types.h>
64 #include "prototypes.h"
65 #include "defines.h"
66 #include "exitcodes.h"
67 #include "pwauth.h"
68 #include "getdef.h"
69 #ifdef USE_PAM
70 #include "pam_defs.h"
71 #endif
72 /*
73  * Assorted #defines to control su's behavior
74  */
75 /*
76  * Global variables
77  */
78 /* not needed by sulog.c anymore */
79 static char name[BUFSIZ];
80 static char oldname[BUFSIZ];
81
82 /* If nonzero, change some environment vars to indicate the user su'd to. */
83 static bool change_environment;
84
85 #ifdef USE_PAM
86 static pam_handle_t *pamh = NULL;
87 static bool caught = false;
88 #endif
89
90 static char *Prog;
91 extern struct passwd pwent;
92
93 /*
94  * External identifiers
95  */
96
97 extern char **newenvp;
98 extern char **environ;
99 extern size_t newenvc;
100
101 /* local function prototypes */
102
103 #ifndef USE_PAM
104
105 static RETSIGTYPE die (int);
106 static int iswheel (const char *);
107
108 /*
109  * die - set or reset termio modes.
110  *
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.
114  */
115 static RETSIGTYPE die (int killed)
116 {
117         static TERMIO sgtty;
118
119         if (killed)
120                 STTY (0, &sgtty);
121         else
122                 GTTY (0, &sgtty);
123
124         if (killed) {
125                 closelog ();
126                 exit (killed);
127         }
128 }
129
130 static int iswheel (const char *username)
131 {
132         struct group *grp;
133
134         grp = getgrnam ("wheel"); /* !USE_PAM, no need for xgetgrnam */
135         if (!grp || !grp->gr_mem)
136                 return 0;
137         return is_on_list (grp->gr_mem, username);
138 }
139 #endif                          /* !USE_PAM */
140
141 /* borrowed from GNU sh-utils' "su.c" */
142 static bool restricted_shell (const char *shellstr)
143 {
144         char *line;
145
146         setusershell ();
147         while ((line = getusershell ()) != NULL) {
148                 if (('#' != *line) && (strcmp (line, shellstr) == 0)) {
149                         endusershell ();
150                         return false;
151                 }
152         }
153         endusershell ();
154         return true;
155 }
156
157 static void su_failure (const char *tty)
158 {
159         sulog (tty, 0, oldname, name);  /* log failed attempt */
160 #ifdef USE_SYSLOG
161         if (getdef_bool ("SYSLOG_SU_ENAB"))
162                 SYSLOG (((0 != pwent.pw_uid) ? LOG_INFO : LOG_NOTICE,
163                          "- %s %s:%s", tty,
164                          ('\0' != oldname[0]) ? oldname : "???",
165                          ('\0' != name[0]) ? name : "???"));
166         closelog ();
167 #endif
168         exit (1);
169 }
170
171
172 #ifdef USE_PAM
173 /* Signal handler for parent process later */
174 static void catch_signals (unused int sig)
175 {
176         caught = true;
177 }
178
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
181  * su.c from shadow.
182  */
183 static void run_shell (const char *shellstr, char *args[], bool doshell,
184                        char *const envp[])
185 {
186         pid_t child;
187         sigset_t ourset;
188         int status;
189         int ret;
190
191         child = fork ();
192         if (child == 0) {       /* child shell */
193                 /*
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);
198                  */
199
200                 if (doshell) {
201                         (void) shell (shellstr, (char *) args[0], envp);
202                 } else {
203                         (void) execve (shellstr, (char **) args, envp);
204                 }
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));
209                 closelog ();
210                 exit (1);
211         }
212         /* parent only */
213         sigfillset (&ourset);
214         if (sigprocmask (SIG_BLOCK, &ourset, NULL) != 0) {
215                 (void) fprintf (stderr, "%s: signal malfunction\n", Prog);
216                 caught = true;
217         }
218         if (!caught) {
219                 struct sigaction action;
220
221                 action.sa_handler = catch_signals;
222                 sigemptyset (&action.sa_mask);
223                 action.sa_flags = 0;
224                 sigemptyset (&ourset);
225
226                 if (   (sigaddset (&ourset, SIGTERM) != 0)
227                     || (sigaddset (&ourset, SIGALRM) != 0)
228                     || (sigaction (SIGTERM, &action, NULL) != 0)
229                     || (sigprocmask (SIG_UNBLOCK, &ourset, NULL) != 0)
230                     ) {
231                         fprintf (stderr,
232                                  "%s: signal masking malfunction\n", Prog);
233                         caught = true;
234                 }
235         }
236
237         if (!caught) {
238                 do {
239                         pid_t pid;
240
241                         pid = waitpid (-1, &status, WUNTRACED);
242
243                         if (((pid_t)-1 != pid) && (0 != WIFSTOPPED (status))) {
244                                 /* The child (shell) was suspended.
245                                  * Suspend su. */
246                                 kill (getpid (), WSTOPSIG(status));
247                                 /* wake child when resumed */
248                                 kill (pid, SIGCONT);
249                         }
250                 } while (0 != WIFSTOPPED (status));
251         }
252
253         if (caught) {
254                 fprintf (stderr, "\nSession terminated, killing shell...");
255                 kill (child, SIGTERM);
256         }
257
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);
264                 exit (1);
265         }
266
267         ret = pam_end (pamh, PAM_SUCCESS);
268
269         if (caught) {
270                 sleep (2);
271                 kill (child, SIGKILL);
272                 fprintf (stderr, " ...killed.\n");
273                 exit (-1);
274         }
275
276         exit ((0 != WIFEXITED (status)) ? WEXITSTATUS (status)
277                                         : WTERMSIG (status) + 128);
278 }
279 #endif
280
281 /*
282  * usage - print command line syntax and exit
283   */
284 static void usage (void)
285 {
286         fputs (_("Usage: su [options] [LOGIN]\n"
287                  "\n"
288                  "Options:\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"
292                  "  -m, -p,\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"
296                  "\n"), stderr);
297         exit (E_USAGE);
298 }
299
300 /*
301  * su - switch user id
302  *
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.
305  *
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.
309  */
310 int main (int argc, char **argv)
311 {
312         char *cp;
313         const char *tty = NULL; /* Name of tty SU is run from        */
314         bool doshell = false;
315         bool fakelogin = false;
316         bool amroot = false;
317         uid_t my_uid;
318         struct passwd *pw = NULL;
319         char **envp = environ;
320         char *shellstr = NULL;
321         char *command = NULL;
322
323 #ifdef USE_PAM
324         char **envcp;
325         int ret;
326 #else                           /* !USE_PAM */
327         int err = 0;
328
329         RETSIGTYPE (*oldsig) (int);
330         int is_console = 0;
331
332         struct spwd *spwd = 0;
333
334 #ifdef SU_ACCESS
335         char *oldpass;
336 #endif
337 #endif                          /* !USE_PAM */
338
339         sanitize_env ();
340
341         (void) setlocale (LC_ALL, "");
342         (void) bindtextdomain (PACKAGE, LOCALEDIR);
343         (void) textdomain (PACKAGE);
344
345         change_environment = true;
346
347         /*
348          * Get the program name. The program name is used as a prefix to
349          * most error messages.
350          */
351         Prog = Basename (argv[0]);
352
353         OPENLOG ("su");
354
355         /*
356          * Process the command line arguments. 
357          */
358
359         {
360                 /*
361                  * Parse the command line options.
362                  */
363                 int option_index = 0;
364                 int c;
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'}
372                 };
373
374                 while ((c =
375                         getopt_long (argc, argv, "c:hlmps:", long_options,
376                                      &option_index)) != -1) {
377                         switch (c) {
378                         case 'c':
379                                 command = optarg;
380                                 break;
381                         case 'h':
382                                 usage ();
383                                 break;
384                         case 'l':
385                                 fakelogin = true;
386                                 break;
387                         case 'm':
388                         case 'p':
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.
392                                  */
393                                 change_environment = false;
394                                 break;
395                         case 's':
396                                 shellstr = optarg;
397                                 break;
398                         default:
399                                 usage ();       /* NOT REACHED */
400                         }
401                 }
402
403                 if ((optind < argc) && (strcmp (argv[optind], "-") == 0)) {
404                         fakelogin = true;
405                         optind++;
406                         if (   (optind < argc)
407                             && (strcmp (argv[optind], "--") == 0)) {
408                                 optind++;
409                         }
410                 }
411         }
412
413         initenv ();
414
415         my_uid = getuid ();
416         amroot = (my_uid == 0);
417
418         /*
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.
421          */
422         cp = ttyname (0);
423         if ((isatty (0) != 0) && (NULL != cp)) {
424                 if (strncmp (cp, "/dev/", 5) == 0) {
425                         tty = cp + 5;
426                 } else {
427                         tty = cp;
428                 }
429 #ifndef USE_PAM
430                 is_console = console (tty);
431 #endif
432         } else {
433                 /*
434                  * Be more paranoid, like su from SimplePAMApps.  --marekm
435                  */
436                 if (!amroot) {
437                         fprintf (stderr,
438                                  _("%s: must be run from a terminal\n"), Prog);
439                         exit (1);
440                 }
441                 tty = "???";
442         }
443
444         /*
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.
449          */
450         if ((optind < argc) && ('-' != argv[optind][0])) {
451                 STRFCPY (name, argv[optind++]); /* use this login id */
452                 if ((optind < argc) && (strcmp (argv[optind], "--") == 0)) {
453                         optind++;
454                 }
455         }
456         if ('\0' == name[0]) {          /* use default user ID */
457                 (void) strcpy (name, "root");
458         }
459
460         doshell = (argc == optind);     /* any arguments remaining? */
461         if (NULL != command) {
462                 doshell = false;
463         }
464
465         /*
466          * Get the user's real name. The current UID is used to determine
467          * who has executed su. That user ID must exist.
468          */
469         pw = get_my_pwent ();
470         if (NULL == pw) {
471                 SYSLOG ((LOG_CRIT, "Unknown UID: %u", my_uid));
472                 su_failure (tty);
473         }
474         STRFCPY (oldname, pw->pw_name);
475
476 #ifndef USE_PAM
477 #ifdef SU_ACCESS
478         /*
479          * Sort out the password of user calling su, in case needed later
480          * -- chris
481          */
482         spwd = getspnam (oldname); /* !USE_PAM, no need for xgetspnam */
483         if (NULL != spwd) {
484                 pw->pw_passwd = spwd->sp_pwdp;
485         }
486         oldpass = xstrdup (pw->pw_passwd);
487 #endif                          /* SU_ACCESS */
488
489 #else                           /* USE_PAM */
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"),
494                                  Prog, ret));
495                 exit (1);
496         }
497
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);
501         }
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));
506                 pam_end (pamh, ret);
507                 exit (1);
508         }
509 #endif                          /* USE_PAM */
510
511       top:
512         /*
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.
516          *
517          * The password file entries for the user is gotten and the account
518          * validated.
519          */
520         pw = xgetpwnam (name);
521         if (NULL == pw) {
522                 (void) fprintf (stderr, _("Unknown id: %s\n"), name);
523                 closelog ();
524                 exit (1);
525         }
526 #ifndef USE_PAM
527         spwd = NULL;
528         if (strcmp (pw->pw_passwd, SHADOW_PASSWD_STRING) == 0) {
529                 spwd = getspnam (name); /* !USE_PAM, no need for xgetspnam */
530                 if (NULL != spwd) {
531                         pw->pw_passwd = spwd->sp_pwdp;
532                 }
533         }
534 #endif                          /* !USE_PAM */
535         pwent = *pw;
536
537         /* If su is not called by root, and the target user has a restricted
538          * shell, the environment must be changed.
539          */
540         change_environment |= (restricted_shell (pwent.pw_shell) && !amroot);
541
542         /*
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)
547          */
548         if (fakelogin && change_environment) {
549                 /*
550                  * The terminal type will be left alone if it is present in
551                  * the environment already.
552                  */
553                 cp = getenv ("TERM");
554                 if (NULL != cp) {
555                         addenv ("TERM", cp);
556                 }
557 #ifndef USE_PAM
558                 cp = getdef_str ("ENV_TZ");
559                 if (NULL != cp) {
560                         addenv (('/' == *cp) ? tz (cp) : cp, NULL);
561                 }
562
563                 /*
564                  * The clock frequency will be reset to the login value if required
565                  */
566                 cp = getdef_str ("ENV_HZ");
567                 if (NULL != cp) {
568                         addenv (cp, NULL);      /* set the default $HZ, if one */
569                 }
570
571                 /*
572                  * Also leave DISPLAY and XAUTHORITY if present, else
573                  * pam_xauth will not work.
574                  */
575                 cp = getenv ("DISPLAY");
576                 if (NULL != cp) {
577                         addenv ("DISPLAY", cp);
578                 }
579                 cp = getenv ("XAUTHORITY");
580                 if (NULL != cp) {
581                         addenv ("XAUTHORITY", cp);
582                 }
583 #endif                          /* !USE_PAM */
584         } else {
585                 while (NULL != *envp) {
586                         addenv (*envp, NULL);
587                         envp++;
588                 }
589         }
590
591 #ifndef USE_PAM
592         /*
593          * BSD systems only allow "wheel" to SU to root. USG systems don't,
594          * so we make this a configurable option.
595          */
596
597         /* The original Shadow 3.3.2 did this differently. Do it like BSD:
598          *
599          * - check for UID 0 instead of name "root" - there are systems with
600          *   several root accounts under different names,
601          *
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).
604          *
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>.
608          */
609
610         if (!amroot) {
611                 if (   (0 == pwent.pw_uid)
612                     && getdef_bool ("SU_WHEEL_ONLY")
613                     && !iswheel (oldname)) {
614                         fprintf (stderr,
615                                  _("You are not authorized to su %s\n"), name);
616                         exit (1);
617                 }
618 #ifdef SU_ACCESS
619                 switch (check_su_auth (oldname, name)) {
620                 case 0: /* normal su, require target user's password */
621                         break;
622                 case 1: /* require no password */
623                         pwent.pw_passwd = "";   /* XXX warning: const */
624                         break;
625                 case 2: /* require own password */
626                         puts (_("(Enter your own password)"));
627                         pwent.pw_passwd = oldpass;
628                         break;
629                 default:        /* access denied (-1) or unexpected value */
630                         fprintf (stderr,
631                                  _("You are not authorized to su %s\n"), name);
632                         exit (1);
633                 }
634 #endif                          /* SU_ACCESS */
635         }
636 #endif                          /* !USE_PAM */
637
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)
641          */
642         if ((NULL == shellstr) && !change_environment) {
643                 shellstr = getenv ("SHELL");
644         }
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
647          */
648         if (   (NULL != shellstr)
649             && !amroot
650             && restricted_shell (pwent.pw_shell)) {
651                 shellstr = NULL;
652         }
653         /* If the shell is not set at this time, use the shell specified
654          * in /etc/passwd.
655          */
656         if (NULL == shellstr) {
657                 shellstr = (char *) strdup (pwent.pw_shell);
658         }
659
660         /*
661          * Set the default shell.
662          */
663         if ((NULL == shellstr) || ('\0' == shellstr[0])) {
664                 shellstr = "/bin/sh";
665         }
666
667         (void) signal (SIGINT, SIG_IGN);
668         (void) signal (SIGQUIT, SIG_IGN);
669 #ifdef USE_PAM
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);
676                 su_failure (tty);
677         }
678
679         ret = pam_acct_mgmt (pamh, 0);
680         if (PAM_SUCCESS != ret) {
681                 if (amroot) {
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);
692                                 su_failure (tty);
693                         }
694                 } else {
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);
700                         su_failure (tty);
701                 }
702         }
703 #else                           /* !USE_PAM */
704         /*
705          * Set up a signal handler in case the user types QUIT.
706          */
707         die (0);
708         (void) oldsig = signal (SIGQUIT, die);
709
710         /*
711          * See if the system defined authentication method is being used. 
712          * The first character of an administrator defined method is an '@'
713          * character.
714          */
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));
718                 su_failure (tty);
719         }
720         (void) signal (SIGQUIT, oldsig);
721
722         /*
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
725          * expired password.
726          */
727         if (!amroot) {
728                 if (NULL == spwd) {
729                         spwd = pwd_to_spwd (&pwent);
730                 }
731
732                 if (expire (&pwent, spwd)) {
733                         /* !USE_PAM, no need for xgetpwnam */
734                         struct passwd *pwd = getpwnam (name);
735
736                         /* !USE_PAM, no need for xgetspnam */
737                         spwd = getspnam (name);
738                         if (NULL != pwd) {
739                                 pwent = *pwd;
740                         }
741                 }
742         }
743
744         /*
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
748          * the account.
749          */
750         if (!amroot) {
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",
754                                  oldname, name));
755                         su_failure (tty);
756                 }
757         }
758 #endif                          /* !USE_PAM */
759
760         (void) signal (SIGINT, SIG_DFL);
761         (void) signal (SIGQUIT, SIG_DFL);
762
763         cp = getdef_str ((pwent.pw_uid == 0) ? "ENV_SUPATH" : "ENV_PATH");
764         if (NULL == cp) {
765                 addenv ("PATH=/bin:/usr/bin", NULL);
766         } else if (strchr (cp, '=') != NULL) {
767                 addenv (cp, NULL);
768         } else {
769                 addenv ("PATH", cp);
770         }
771
772         if (getenv ("IFS") != NULL) {   /* don't export user IFS ... */
773                 addenv ("IFS= \t\n", NULL);     /* ... instead, set a safe IFS */
774         }
775
776         /*
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).
780          */
781         if ('*' == pwent.pw_shell[0]) { /* subsystem root required */
782                 pwent.pw_shell++;       /* skip the '*' */
783                 subsystem (&pwent);     /* figure out what to execute */
784                 endpwent ();
785                 endspent ();
786                 goto top;
787         }
788
789         sulog (tty, true, oldname, name);       /* save SU information */
790         endpwent ();
791         endspent ();
792 #ifdef USE_SYSLOG
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 : "???"));
797         }
798 #endif
799
800 #ifdef USE_PAM
801         /* set primary group id and supplementary groups */
802         if (setup_groups (&pwent) != 0) {
803                 pam_end (pamh, PAM_ABORT);
804                 exit (1);
805         }
806
807         /*
808          * pam_setcred() may do things like resource limits, console groups,
809          * and much more, depending on the configured modules
810          */
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);
816                 exit (1);
817         }
818
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);
826                 exit (1);
827         }
828
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
833                  */
834                 environ = newenvp;      /* make new environment active */
835
836                 /* update environment with all pam set variables */
837                 envcp = pam_getenvlist (pamh);
838                 if (NULL != envcp) {
839                         while (NULL != *envcp) {
840                                 addenv (*envcp, NULL);
841                                 envcp++;
842                         }
843                 }
844         }
845
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);
851                 exit (1);
852         }
853 #else                           /* !USE_PAM */
854         environ = newenvp;      /* make new environment active */
855
856         /* no limits if su from root (unless su must fake login's behavior) */
857         if (!amroot || fakelogin) {
858                 setup_limits (&pwent);
859         }
860
861         if (setup_uid_gid (&pwent, is_console) != 0) {
862                 exit (1);
863         }
864 #endif                          /* !USE_PAM */
865
866         if (change_environment) {
867                 if (fakelogin) {
868                         pwent.pw_shell = shellstr;
869                         setup_env (&pwent);
870                 } else {
871                         addenv ("HOME", pwent.pw_dir);
872                         addenv ("USER", pwent.pw_name);
873                         addenv ("LOGNAME", pwent.pw_name);
874                         addenv ("SHELL", shellstr);
875                 }
876         }
877
878         /*
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
884          */
885         closelog ();
886
887         /*
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.
890          */
891         if (fakelogin) {
892                 char *arg0;
893
894                 cp = getdef_str ("SU_NAME");
895                 if (NULL == cp) {
896                         cp = Basename (shellstr);
897                 }
898
899                 arg0 = xmalloc (strlen (cp) + 2);
900                 arg0[0] = '-';
901                 strcpy (arg0 + 1, cp);
902                 cp = arg0;
903         } else {
904                 cp = Basename (shellstr);
905         }
906
907         if (!doshell) {
908                 /* Position argv to the remaining arguments */
909                 argv += optind;
910                 if (NULL != command) {
911                         argv -= 2;
912                         argv[0] = "-c";
913                         argv[1] = command;
914                 }
915                 /*
916                  * Use the shell and create an argv
917                  * with the rest of the command line included.
918                  */
919                 argv[-1] = shellstr;
920 #ifndef USE_PAM
921                 (void) execve (shellstr, &argv[-1], environ);
922                 err = errno;
923                 (void) fputs (_("No shell\n"), stderr);
924                 SYSLOG ((LOG_WARN, "Cannot execute %s", shellstr));
925                 closelog ();
926                 exit ((ENOENT == err) ? E_CMD_NOTFOUND : E_CMD_NOEXEC);
927 #else
928                 run_shell (shellstr, &argv[-1], false, environ); /* no return */
929 #endif
930         }
931 #ifndef USE_PAM
932         err = shell (shellstr, cp, environ);
933         exit ((ENOENT == err) ? E_CMD_NOTFOUND : E_CMD_NOEXEC);
934 #else
935         run_shell (shellstr, &cp, true, environ);
936 #endif
937         /* NOT REACHED */
938         exit (1);
939 }
940