]> granicus.if.org Git - shadow/blob - src/su.c
a48e5296f7f11a74c04917a944119db70b7d0138
[shadow] / src / su.c
1 /*
2  * Copyright 1989 - 1994, Julianne Frances Haugh
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
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.
16  *
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
27  * SUCH DAMAGE.
28  */
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.
32
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)
36    any later version.
37
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.
42
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.  */
46
47
48 #include <config.h>
49
50 #ident "$Id$"
51
52 #include <getopt.h>
53 #include <grp.h>
54 #include <pwd.h>
55 #include <signal.h>
56 #include <stdio.h>
57 #include <sys/types.h>
58 #include "prototypes.h"
59 #include "defines.h"
60 #include "exitcodes.h"
61 #include "pwauth.h"
62 #include "getdef.h"
63 #ifdef USE_PAM
64 #include "pam_defs.h"
65 #endif
66 /*
67  * Assorted #defines to control su's behavior
68  */
69 /*
70  * Global variables
71  */
72 /* not needed by sulog.c anymore */
73 static char name[BUFSIZ];
74 static char oldname[BUFSIZ];
75
76 /* If nonzero, change some environment vars to indicate the user su'd to. */
77 static int change_environment;
78
79 #ifdef USE_PAM
80 static pam_handle_t *pamh = NULL;
81 static int caught = 0;
82 #endif
83
84 static char *Prog;
85 extern struct passwd pwent;
86
87 /*
88  * External identifiers
89  */
90
91 extern char **newenvp;
92 extern char **environ;
93 extern size_t newenvc;
94
95 /* local function prototypes */
96
97 #ifndef USE_PAM
98
99 static RETSIGTYPE die (int);
100 static int iswheel (const char *);
101
102 /*
103  * die - set or reset termio modes.
104  *
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.
108  */
109 static RETSIGTYPE die (int killed)
110 {
111         static TERMIO sgtty;
112
113         if (killed)
114                 STTY (0, &sgtty);
115         else
116                 GTTY (0, &sgtty);
117
118         if (killed) {
119                 closelog ();
120                 exit (killed);
121         }
122 }
123
124 static int iswheel (const char *username)
125 {
126         struct group *grp;
127
128         grp = getgrnam ("wheel");;
129         if (!grp || !grp->gr_mem)
130                 return 0;
131         return is_on_list (grp->gr_mem, username);
132 }
133 #endif                          /* !USE_PAM */
134
135 /* borrowed from GNU sh-utils' "su.c" */
136 static int restricted_shell (const char *shellstr)
137 {
138         char *line;
139
140         setusershell ();
141         while ((line = getusershell ()) != NULL) {
142                 if (*line != '#' && strcmp (line, shellstr) == 0) {
143                         endusershell ();
144                         return 0;
145                 }
146         }
147         endusershell ();
148         return 1;
149 }
150
151 static void su_failure (const char *tty)
152 {
153         sulog (tty, 0, oldname, name);  /* log failed attempt */
154 #ifdef USE_SYSLOG
155         if (getdef_bool ("SYSLOG_SU_ENAB"))
156                 SYSLOG ((pwent.pw_uid ? LOG_INFO : LOG_NOTICE,
157                          "- %s %s:%s", tty,
158                          oldname[0] ? oldname : "???", name[0] ? name : "???"));
159         closelog ();
160 #endif
161         exit (1);
162 }
163
164
165 #ifdef USE_PAM
166 /* Signal handler for parent process later */
167 static void catch_signals (int sig)
168 {
169         ++caught;
170 }
171
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
174  * su.c from shadow.
175  */
176 static void run_shell (const char *shellstr, char *args[], int doshell,
177                        char *const envp[])
178 {
179         int child;
180         sigset_t ourset;
181         int status;
182         int ret;
183
184         child = fork ();
185         if (child == 0) {       /* child shell */
186                 pam_end (pamh, PAM_SUCCESS);
187
188                 if (doshell)
189                         (void) shell (shellstr, (char *) args[0], envp);
190                 else
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));
196                 closelog ();
197                 exit (1);
198         }
199         /* parent only */
200         sigfillset (&ourset);
201         if (sigprocmask (SIG_BLOCK, &ourset, NULL)) {
202                 (void) fprintf (stderr, "%s: signal malfunction\n", Prog);
203                 caught = 1;
204         }
205         if (!caught) {
206                 struct sigaction action;
207
208                 action.sa_handler = catch_signals;
209                 sigemptyset (&action.sa_mask);
210                 action.sa_flags = 0;
211                 sigemptyset (&ourset);
212
213                 if (sigaddset (&ourset, SIGTERM)
214                     || sigaddset (&ourset, SIGALRM)
215                     || sigaction (SIGTERM, &action, NULL)
216                     || sigprocmask (SIG_UNBLOCK, &ourset, NULL)
217                     ) {
218                         fprintf (stderr,
219                                  "%s: signal masking malfunction\n", Prog);
220                         caught = 1;
221                 }
222         }
223
224         if (!caught) {
225                 do {
226                         int pid;
227
228                         pid = waitpid (-1, &status, WUNTRACED);
229
230                         if (WIFSTOPPED (status)) {
231                                 kill (getpid (), SIGSTOP);
232                                 /* once we get here, we must have resumed */
233                                 kill (pid, SIGCONT);
234                         }
235                 } while (WIFSTOPPED (status));
236         }
237
238         if (caught) {
239                 fprintf (stderr, "\nSession terminated, killing shell...");
240                 kill (child, SIGTERM);
241         }
242
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));
248                 pam_end (pamh, ret);
249                 exit (1);
250         }
251
252         ret = pam_end (pamh, PAM_SUCCESS);
253
254         if (caught) {
255                 sleep (2);
256                 kill (child, SIGKILL);
257                 fprintf (stderr, " ...killed.\n");
258                 exit (-1);
259         }
260
261         exit (WIFEXITED (status)
262               ? WEXITSTATUS (status)
263               : WTERMSIG (status) + 128);
264 }
265 #endif
266
267 /*
268  * usage - print command line syntax and exit
269   */
270 static void usage (void)
271 {
272         fprintf (stderr, _("Usage: su [options] [LOGIN]\n"
273                            "\n"
274                            "Options:\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"
278                            "  -m, -p,\n"
279                            "  --preserve-environment    do not reset environment variables, and keep\n"
280                            "                            the same shell\n"
281                            "  -s, --shell SHELL         use SHELL instead of the default in passwd\n"
282                            "\n"));
283         exit (E_USAGE);
284 }
285
286 /*
287  * su - switch user id
288  *
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.
291  *
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.
295  */
296 int main (int argc, char **argv)
297 {
298         char *cp;
299         const char *tty = 0;    /* Name of tty SU is run from        */
300         int doshell = 0;
301         int fakelogin = 0;
302         int amroot = 0;
303         uid_t my_uid;
304         struct passwd *pw = 0;
305         char **envp = environ;
306         char *shellstr = 0, *command = 0;
307
308 #ifdef USE_PAM
309         char **envcp;
310         int ret;
311 #else                           /* !USE_PAM */
312         int err = 0;
313
314         RETSIGTYPE (*oldsig) ();
315         int is_console = 0;
316
317         struct spwd *spwd = 0;
318
319 #ifdef SU_ACCESS
320         char *oldpass;
321 #endif
322 #endif                          /* !USE_PAM */
323
324         sanitize_env ();
325
326         setlocale (LC_ALL, "");
327         bindtextdomain (PACKAGE, LOCALEDIR);
328         textdomain (PACKAGE);
329
330         change_environment = 1;
331
332         /*
333          * Get the program name. The program name is used as a prefix to
334          * most error messages.
335          */
336         Prog = Basename (argv[0]);
337
338         OPENLOG ("su");
339
340         /*
341          * Process the command line arguments. 
342          */
343
344         {
345                 /*
346                  * Parse the command line options.
347                  */
348                 int option_index = 0;
349                 int c;
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'}
357                 };
358
359                 while ((c =
360                         getopt_long (argc, argv, "-c:hlmps:", long_options,
361                                      &option_index)) != -1) {
362                         switch (c) {
363                         case 1:
364                                 /* this is not an su option */
365                                 /* The next arguments are either '-', the
366                                  * target name, or arguments to be passed
367                                  * to the shell.
368                                  */
369                                 /* rewind the (not yet handled) option */
370                                 optind--;
371                                 goto end_su_options;
372                                 break;  /* NOT REACHED */
373                         case 'c':
374                                 command = optarg;
375                                 break;
376                         case 'h':
377                                 usage ();
378                                 break;
379                         case 'l':
380                                 fakelogin = 1;
381                                 break;
382                         case 'm':
383                         case 'p':
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.
387                                  */
388                                 change_environment = 0;
389                                 break;
390                         case 's':
391                                 shellstr = optarg;
392                                 break;
393                         default:
394                                 usage ();       /* NOT REACHED */
395                         }
396                 }
397               end_su_options:
398                 if (optind < argc && !strcmp (argv[optind], "-")) {
399                         fakelogin = 1;
400                         optind++;
401                         if (optind < argc && !strcmp (argv[optind], "--"))
402                                 optind++;
403                 }
404         }
405
406         initenv ();
407
408         my_uid = getuid ();
409         amroot = (my_uid == 0);
410
411         /*
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.
414          */
415         if (isatty (0) && (cp = ttyname (0))) {
416                 if (strncmp (cp, "/dev/", 5) == 0)
417                         tty = cp + 5;
418                 else
419                         tty = cp;
420 #ifndef USE_PAM
421                 is_console = console (tty);
422 #endif
423         } else {
424                 /*
425                  * Be more paranoid, like su from SimplePAMApps.  --marekm
426                  */
427                 if (!amroot) {
428                         fprintf (stderr,
429                                  _("%s: must be run from a terminal\n"), Prog);
430                         exit (1);
431                 }
432                 tty = "???";
433         }
434
435         /*
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.
440          */
441         if (optind < argc && argv[optind][0] != '-') {
442                 STRFCPY (name, argv[optind++]); /* use this login id */
443                 if (optind < argc && !strcmp (argv[optind], "--"))
444                         optind++;
445         }
446         if (!name[0])           /* use default user ID */
447                 (void) strcpy (name, "root");
448
449         doshell = argc == optind;       /* any arguments remaining? */
450         if (command)
451                 doshell = 0;
452
453         /*
454          * Get the user's real name. The current UID is used to determine
455          * who has executed su. That user ID must exist.
456          */
457         pw = get_my_pwent ();
458         if (!pw) {
459                 SYSLOG ((LOG_CRIT, "Unknown UID: %u", my_uid));
460                 su_failure (tty);
461         }
462         STRFCPY (oldname, pw->pw_name);
463
464 #ifndef USE_PAM
465 #ifdef SU_ACCESS
466         /*
467          * Sort out the password of user calling su, in case needed later
468          * -- chris
469          */
470         if ((spwd = getspnam (oldname)))
471                 pw->pw_passwd = spwd->sp_pwdp;
472         oldpass = xstrdup (pw->pw_passwd);
473 #endif                          /* SU_ACCESS */
474
475 #else                           /* USE_PAM */
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"),
480                                  Prog, ret));
481                 exit (1);
482         }
483
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));
491                 pam_end (pamh, ret);
492                 exit (1);
493         }
494 #endif                          /* USE_PAM */
495
496       top:
497         /*
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.
501          *
502          * The password file entries for the user is gotten and the account
503          * validated.
504          */
505         if (!(pw = getpwnam (name))) {
506                 (void) fprintf (stderr, _("Unknown id: %s\n"), name);
507                 closelog ();
508                 exit (1);
509         }
510 #ifndef USE_PAM
511         spwd = NULL;
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 */
516         pwent = *pw;
517
518         /* If su is not called by root, and the target user has a restricted
519          * shell, the environment must be changed.
520          */
521         change_environment |= (restricted_shell (pwent.pw_shell) && !amroot);
522
523         /*
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)
528          */
529         if (fakelogin && change_environment) {
530                 /*
531                  * The terminal type will be left alone if it is present in
532                  * the environment already.
533                  */
534                 if ((cp = getenv ("TERM")))
535                         addenv ("TERM", cp);
536 #ifndef USE_PAM
537                 if ((cp = getdef_str ("ENV_TZ")))
538                         addenv (*cp == '/' ? tz (cp) : cp, NULL);
539
540                 /*
541                  * The clock frequency will be reset to the login value if required
542                  */
543                 if ((cp = getdef_str ("ENV_HZ")))
544                         addenv (cp, NULL);      /* set the default $HZ, if one */
545
546                 /*
547                  * Also leave DISPLAY and XAUTHORITY if present, else
548                  * pam_xauth will not work.
549                  */
550                 if ((cp = getenv ("DISPLAY")))
551                         addenv ("DISPLAY", cp);
552                 if ((cp = getenv ("XAUTHORITY")))
553                         addenv ("XAUTHORITY", cp);
554 #endif                          /* !USE_PAM */
555         } else {
556                 while (*envp)
557                         addenv (*envp++, NULL);
558         }
559
560 #ifndef USE_PAM
561         /*
562          * BSD systems only allow "wheel" to SU to root. USG systems don't,
563          * so we make this a configurable option.
564          */
565
566         /* The original Shadow 3.3.2 did this differently. Do it like BSD:
567          *
568          * - check for UID 0 instead of name "root" - there are systems with
569          *   several root accounts under different names,
570          *
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).
573          *
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>.
577          */
578
579         if (!amroot) {
580                 if (pwent.pw_uid == 0 && getdef_bool ("SU_WHEEL_ONLY")
581                     && !iswheel (oldname)) {
582                         fprintf (stderr,
583                                  _("You are not authorized to su %s\n"), name);
584                         exit (1);
585                 }
586 #ifdef SU_ACCESS
587                 switch (check_su_auth (oldname, name)) {
588                 case 0: /* normal su, require target user's password */
589                         break;
590                 case 1: /* require no password */
591                         pwent.pw_passwd = "";   /* XXX warning: const */
592                         break;
593                 case 2: /* require own password */
594                         puts (_("(Enter your own password)"));
595                         pwent.pw_passwd = oldpass;
596                         break;
597                 default:        /* access denied (-1) or unexpected value */
598                         fprintf (stderr,
599                                  _("You are not authorized to su %s\n"), name);
600                         exit (1);
601                 }
602 #endif                          /* SU_ACCESS */
603         }
604 #endif                          /* !USE_PAM */
605
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)
609          */
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
614          */
615         if (shellstr != NULL && !amroot && restricted_shell (pwent.pw_shell))
616                 shellstr = NULL;
617         /* If the shell is not set at this time, use the shell specified
618          * in /etc/passwd.
619          */
620         if (shellstr == NULL)
621                 shellstr = (char *) strdup (pwent.pw_shell);
622
623         /*
624          * Set the default shell.
625          */
626         if (shellstr == NULL || shellstr[0] == '\0')
627                 shellstr = "/bin/sh";
628
629         signal (SIGINT, SIG_IGN);
630         signal (SIGQUIT, SIG_IGN);
631 #ifdef USE_PAM
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));
637                 pam_end (pamh, ret);
638                 su_failure (tty);
639         }
640
641         ret = pam_acct_mgmt (pamh, 0);
642         if (ret != PAM_SUCCESS) {
643                 if (amroot) {
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));
653                                 pam_end (pamh, ret);
654                                 su_failure (tty);
655                         }
656                 } else {
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));
661                         pam_end (pamh, ret);
662                         su_failure (tty);
663                 }
664         }
665 #else                           /* !USE_PAM */
666         /*
667          * Set up a signal handler in case the user types QUIT.
668          */
669         die (0);
670         oldsig = signal (SIGQUIT, die);
671
672         /*
673          * See if the system defined authentication method is being used. 
674          * The first character of an administrator defined method is an '@'
675          * character.
676          */
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));
680                 su_failure (tty);
681         }
682         signal (SIGQUIT, oldsig);
683
684         /*
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
687          * expired password.
688          */
689         if (!amroot) {
690                 if (!spwd)
691                         spwd = pwd_to_spwd (&pwent);
692
693                 if (expire (&pwent, spwd)) {
694                         struct passwd *pwd = getpwnam (name);
695
696                         spwd = getspnam (name);
697                         if (pwd)
698                                 pwent = *pwd;
699                 }
700         }
701
702         /*
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
706          * the account.
707          */
708         if (!amroot) {
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",
712                                  oldname, name));
713                         su_failure (tty);
714                 }
715         }
716 #endif                          /* !USE_PAM */
717
718         signal (SIGINT, SIG_DFL);
719         signal (SIGQUIT, SIG_DFL);
720
721         cp = getdef_str ((pwent.pw_uid == 0) ? "ENV_SUPATH" : "ENV_PATH");
722         if (!cp) {
723                 addenv ("PATH=/bin:/usr/bin", NULL);
724         } else if (strchr (cp, '=')) {
725                 addenv (cp, NULL);
726         } else {
727                 addenv ("PATH", cp);
728         }
729
730         if (getenv ("IFS"))     /* don't export user IFS ... */
731                 addenv ("IFS= \t\n", NULL);     /* ... instead, set a safe IFS */
732
733         /*
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).
737          */
738         if (pwent.pw_shell[0] == '*') { /* subsystem root required */
739                 pwent.pw_shell++;       /* skip the '*' */
740                 subsystem (&pwent);     /* figure out what to execute */
741                 endpwent ();
742                 endspent ();
743                 goto top;
744         }
745
746         sulog (tty, 1, oldname, name);  /* save SU information */
747         endpwent ();
748         endspent ();
749 #ifdef USE_SYSLOG
750         if (getdef_bool ("SYSLOG_SU_ENAB"))
751                 SYSLOG ((LOG_INFO, "+ %s %s:%s", tty,
752                          oldname[0] ? oldname : "???", name[0] ? name : "???"));
753 #endif
754
755 #ifdef USE_PAM
756         /* set primary group id and supplementary groups */
757         if (setup_groups (&pwent)) {
758                 pam_end (pamh, PAM_ABORT);
759                 exit (1);
760         }
761
762         /*
763          * pam_setcred() may do things like resource limits, console groups,
764          * and much more, depending on the configured modules
765          */
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));
770                 pam_end (pamh, ret);
771                 exit (1);
772         }
773
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);
780                 pam_end (pamh, ret);
781                 exit (1);
782         }
783
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
788                  */
789                 environ = newenvp;      /* make new environment active */
790
791                 /* update environment with all pam set variables */
792                 envcp = pam_getenvlist (pamh);
793                 if (envcp) {
794                         while (*envcp) {
795                                 addenv (*envcp, NULL);
796                                 envcp++;
797                         }
798                 }
799         }
800
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);
806                 exit (1);
807         }
808 #else                           /* !USE_PAM */
809         environ = newenvp;      /* make new environment active */
810
811         /* no limits if su from root (unless su must fake login's behavior) */
812         if (!amroot || fakelogin)
813                 setup_limits (&pwent);
814
815         if (setup_uid_gid (&pwent, is_console))
816                 exit (1);
817 #endif                          /* !USE_PAM */
818
819         if (change_environment) {
820                 if (fakelogin) {
821                         pwent.pw_shell = shellstr;
822                         setup_env (&pwent);
823                 } else {
824                         addenv ("HOME", pwent.pw_dir);
825                         addenv ("USER", pwent.pw_name);
826                         addenv ("LOGNAME", pwent.pw_name);
827                         addenv ("SHELL", shellstr);
828                 }
829         }
830
831         /*
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
837          */
838         closelog ();
839
840         /*
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.
843          */
844         if (fakelogin) {
845                 char *arg0;
846
847                 cp = getdef_str ("SU_NAME");
848                 if (!cp)
849                         cp = Basename (shellstr);
850
851                 arg0 = xmalloc (strlen (cp) + 2);
852                 arg0[0] = '-';
853                 strcpy (arg0 + 1, cp);
854                 cp = arg0;
855         } else
856                 cp = Basename (shellstr);
857
858         if (!doshell) {
859                 /* Position argv to the remaining arguments */
860                 argv += optind;
861                 if (command) {
862                         argv -= 2;
863                         argv[0] = "-c";
864                         argv[1] = command;
865                 }
866                 /*
867                  * Use the shell and create an argv
868                  * with the rest of the command line included.
869                  */
870                 argv[-1] = shellstr;
871 #ifndef USE_PAM
872                 (void) execve (shellstr, &argv[-1], environ);
873                 err = errno;
874                 (void) fprintf (stderr, _("No shell\n"));
875                 SYSLOG ((LOG_WARN, "Cannot execute %s", shellstr));
876                 closelog ();
877                 exit (err == ENOENT ? E_CMD_NOTFOUND : E_CMD_NOEXEC);
878 #else
879                 run_shell (shellstr, &argv[-1], 0, environ);    /* no return */
880 #endif
881         }
882 #ifndef USE_PAM
883         err = shell (shellstr, cp, environ);
884         exit (err == ENOENT ? E_CMD_NOTFOUND : E_CMD_NOEXEC);
885 #else
886         run_shell (shellstr, &cp, 1, environ);
887 #endif
888         /* NOT REACHED */
889         exit (1);
890 }