]> granicus.if.org Git - shadow/blob - src/su.c
* configure.in, libmisc/shell.c, libmisc/setupenv.c, src/newgrp.c,
[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 - 2009, 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 "pwauth.h"
67 #include "getdef.h"
68 #ifdef USE_PAM
69 #include "pam_defs.h"
70 #endif                          /* USE_PAM */
71 /*@-exitarg@*/
72 #include "exitcodes.h"
73
74 /*
75  * Assorted #defines to control su's behavior
76  */
77 /*
78  * Global variables
79  */
80 char *Prog;
81
82 /* not needed by sulog.c anymore */
83 static char name[BUFSIZ];
84 static char oldname[BUFSIZ];
85
86 /* If nonzero, change some environment vars to indicate the user su'd to. */
87 static bool change_environment;
88
89 #ifdef USE_PAM
90 static pam_handle_t *pamh = NULL;
91 static bool caught = false;
92 #endif
93
94 extern struct passwd pwent;
95
96 /*
97  * External identifiers
98  */
99
100 extern char **newenvp;
101 extern char **environ;
102 extern size_t newenvc;
103
104 /* local function prototypes */
105
106 #ifndef USE_PAM
107
108 static RETSIGTYPE die (int);
109 static int iswheel (const char *);
110
111 /*
112  * die - set or reset termio modes.
113  *
114  *      die() is called before processing begins. signal() is then called
115  *      with die() as the signal handler. If signal later calls die() with a
116  *      signal number, the terminal modes are then reset.
117  */
118 static RETSIGTYPE die (int killed)
119 {
120         static TERMIO sgtty;
121
122         if (killed)
123                 STTY (0, &sgtty);
124         else
125                 GTTY (0, &sgtty);
126
127         if (killed) {
128                 closelog ();
129                 exit (killed);
130         }
131 }
132
133 static int iswheel (const char *username)
134 {
135         struct group *grp;
136
137         grp = getgrnam ("wheel"); /* !USE_PAM, no need for xgetgrnam */
138         if (   (NULL ==grp)
139             || (NULL == grp->gr_mem)) {
140                 return 0;
141         }
142         return is_on_list (grp->gr_mem, username);
143 }
144 #endif                          /* !USE_PAM */
145
146 /* borrowed from GNU sh-utils' "su.c" */
147 static bool restricted_shell (const char *shellstr)
148 {
149         char *line;
150
151         setusershell ();
152         while ((line = getusershell ()) != NULL) {
153                 if (('#' != *line) && (strcmp (line, shellstr) == 0)) {
154                         endusershell ();
155                         return false;
156                 }
157         }
158         endusershell ();
159         return true;
160 }
161
162 static void su_failure (const char *tty)
163 {
164         sulog (tty, false, oldname, name);      /* log failed attempt */
165 #ifdef USE_SYSLOG
166         if (getdef_bool ("SYSLOG_SU_ENAB")) {
167                 SYSLOG (((0 != pwent.pw_uid) ? LOG_INFO : LOG_NOTICE,
168                          "- %s %s:%s", tty,
169                          ('\0' != oldname[0]) ? oldname : "???",
170                          ('\0' != name[0]) ? name : "???"));
171         }
172         closelog ();
173 #endif
174         exit (1);
175 }
176
177 /*
178  * execve_shell - Execute a shell with execve, or interpret it with
179  * /bin/sh
180  */
181 void execve_shell (const char *shellstr, char *args[], char *const envp[])
182 {
183         int err;
184         (void) execve (shellstr, (char **) args, envp);
185         err = errno;
186
187         if (access (shellstr, R_OK|X_OK) == 0) {
188                 /*
189                  * Assume this is a shell script (with no shebang).
190                  * Interpret it with /bin/sh
191                  */
192                 size_t n_args = 0;
193                 char **targs;
194                 while (NULL != args[n_args]) {
195                         n_args++;
196                 }
197                 targs = (char **) xmalloc ((n_args + 2) * sizeof (args[0]));
198                 targs[0] = "sh";
199                 targs[1] = xstrdup (shellstr);
200                 targs[n_args+1] = NULL;
201                 while (1 != n_args) {
202                         targs[n_args] = args[n_args - 1];
203                         n_args--;
204                 }
205
206                 (void) execve (SHELL, targs, envp);
207         } else {
208                 errno = err;
209         }
210 }
211
212 #ifdef USE_PAM
213 /* Signal handler for parent process later */
214 static void catch_signals (unused int sig)
215 {
216         caught = true;
217 }
218
219 /* This I ripped out of su.c from sh-utils after the Mandrake pam patch
220  * have been applied.  Some work was needed to get it integrated into
221  * su.c from shadow.
222  */
223 static void run_shell (const char *shellstr, char *args[], bool doshell,
224                        char *const envp[])
225 {
226         pid_t child;
227         sigset_t ourset;
228         int status;
229         int ret;
230
231         child = fork ();
232         if (child == 0) {       /* child shell */
233                 /*
234                  * PAM_DATA_SILENT is not supported by some modules, and
235                  * there is no strong need to clean up the process space's
236                  * memory since we will either call exec or exit.
237                 pam_end (pamh, PAM_SUCCESS | PAM_DATA_SILENT);
238                  */
239
240                 if (doshell) {
241                         (void) shell (shellstr, (char *) args[0], envp);
242                 } else {
243                         execve_shell (shellstr, (char **) args, envp);
244                 }
245
246                 exit (errno == ENOENT ? E_CMD_NOTFOUND : E_CMD_NOEXEC);
247         } else if ((pid_t)-1 == child) {
248                 (void) fprintf (stderr, "%s: Cannot fork user shell\n", Prog);
249                 SYSLOG ((LOG_WARN, "Cannot execute %s", shellstr));
250                 closelog ();
251                 exit (1);
252         }
253         /* parent only */
254         sigfillset (&ourset);
255         if (sigprocmask (SIG_BLOCK, &ourset, NULL) != 0) {
256                 (void) fprintf (stderr, "%s: signal malfunction\n", Prog);
257                 caught = true;
258         }
259         if (!caught) {
260                 struct sigaction action;
261
262                 action.sa_handler = catch_signals;
263                 sigemptyset (&action.sa_mask);
264                 action.sa_flags = 0;
265                 sigemptyset (&ourset);
266
267                 if (   (sigaddset (&ourset, SIGTERM) != 0)
268                     || (sigaddset (&ourset, SIGALRM) != 0)
269                     || (sigaction (SIGTERM, &action, NULL) != 0)
270                     || (sigprocmask (SIG_UNBLOCK, &ourset, NULL) != 0)
271                     ) {
272                         fprintf (stderr,
273                                  "%s: signal masking malfunction\n", Prog);
274                         caught = true;
275                 }
276         }
277
278         if (!caught) {
279                 do {
280                         pid_t pid;
281
282                         pid = waitpid (-1, &status, WUNTRACED);
283
284                         if (((pid_t)-1 != pid) && (0 != WIFSTOPPED (status))) {
285                                 /* The child (shell) was suspended.
286                                  * Suspend su. */
287                                 kill (getpid (), WSTOPSIG(status));
288                                 /* wake child when resumed */
289                                 kill (pid, SIGCONT);
290                         }
291                 } while (0 != WIFSTOPPED (status));
292         }
293
294         if (caught) {
295                 fprintf (stderr, "\nSession terminated, killing shell...");
296                 kill (child, SIGTERM);
297         }
298
299         ret = pam_close_session (pamh, 0);
300         if (PAM_SUCCESS != ret) {
301                 SYSLOG ((LOG_ERR, "pam_close_session: %s",
302                          pam_strerror (pamh, ret)));
303                 fprintf (stderr, _("%s: %s\n"), Prog, pam_strerror (pamh, ret));
304                 (void) pam_end (pamh, ret);
305                 exit (1);
306         }
307
308         ret = pam_end (pamh, PAM_SUCCESS);
309
310         if (caught) {
311                 sleep (2);
312                 kill (child, SIGKILL);
313                 fprintf (stderr, " ...killed.\n");
314                 exit (-1);
315         }
316
317         exit ((0 != WIFEXITED (status)) ? WEXITSTATUS (status)
318                                         : WTERMSIG (status) + 128);
319 }
320 #endif
321
322 /*
323  * usage - print command line syntax and exit
324   */
325 static void usage (void)
326 {
327         fputs (_("Usage: su [options] [LOGIN]\n"
328                  "\n"
329                  "Options:\n"
330                  "  -c, --command COMMAND         pass COMMAND to the invoked shell\n"
331                  "  -h, --help                    display this help message and exit\n"
332                  "  -, -l, --login                make the shell a login shell\n"
333                  "  -m, -p,\n"
334                  "  --preserve-environment        do not reset environment variables, and\n"
335                  "                                keep the same shell\n"
336                  "  -s, --shell SHELL             use SHELL instead of the default in passwd\n"
337                  "\n"), stderr);
338         exit (E_USAGE);
339 }
340
341 /*
342  * su - switch user id
343  *
344  *      su changes the user's ids to the values for the specified user.  if
345  *      no new user name is specified, "root" or UID 0 is used by default.
346  *
347  *      Any additional arguments are passed to the user's shell. In
348  *      particular, the argument "-c" will cause the next argument to be
349  *      interpreted as a command by the common shell programs.
350  */
351 int main (int argc, char **argv)
352 {
353         const char *cp;
354         const char *tty = NULL; /* Name of tty SU is run from        */
355         bool doshell = false;
356         bool fakelogin = false;
357         bool amroot = false;
358         uid_t my_uid;
359         struct passwd *pw = NULL;
360         char **envp = environ;
361         char *shellstr = NULL;
362         char *command = NULL;
363
364 #ifdef USE_PAM
365         char **envcp;
366         int ret;
367 #else                           /* !USE_PAM */
368         int err = 0;
369
370         RETSIGTYPE (*oldsig) (int);
371         int is_console = 0;
372
373         struct spwd *spwd = 0;
374
375 #ifdef SU_ACCESS
376         char *oldpass;
377 #endif
378 #endif                          /* !USE_PAM */
379
380         sanitize_env ();
381
382         (void) setlocale (LC_ALL, "");
383         (void) bindtextdomain (PACKAGE, LOCALEDIR);
384         (void) textdomain (PACKAGE);
385
386         change_environment = true;
387
388         /*
389          * Get the program name. The program name is used as a prefix to
390          * most error messages.
391          */
392         Prog = Basename (argv[0]);
393
394         OPENLOG ("su");
395
396         /*
397          * Process the command line arguments. 
398          */
399
400         {
401                 /*
402                  * Parse the command line options.
403                  */
404                 int option_index = 0;
405                 int c;
406                 static struct option long_options[] = {
407                         {"command", required_argument, NULL, 'c'},
408                         {"help", no_argument, NULL, 'h'},
409                         {"login", no_argument, NULL, 'l'},
410                         {"preserve-environment", no_argument, NULL, 'p'},
411                         {"shell", required_argument, NULL, 's'},
412                         {NULL, 0, NULL, '\0'}
413                 };
414
415                 while ((c =
416                         getopt_long (argc, argv, "c:hlmps:", long_options,
417                                      &option_index)) != -1) {
418                         switch (c) {
419                         case 'c':
420                                 command = optarg;
421                                 break;
422                         case 'h':
423                                 usage ();
424                                 break;
425                         case 'l':
426                                 fakelogin = true;
427                                 break;
428                         case 'm':
429                         case 'p':
430                                 /* This will only have an effect if the target
431                                  * user do not have a restricted shell, or if
432                                  * su is called by root.
433                                  */
434                                 change_environment = false;
435                                 break;
436                         case 's':
437                                 shellstr = optarg;
438                                 break;
439                         default:
440                                 usage ();       /* NOT REACHED */
441                         }
442                 }
443
444                 if ((optind < argc) && (strcmp (argv[optind], "-") == 0)) {
445                         fakelogin = true;
446                         optind++;
447                         if (   (optind < argc)
448                             && (strcmp (argv[optind], "--") == 0)) {
449                                 optind++;
450                         }
451                 }
452         }
453
454         initenv ();
455
456         my_uid = getuid ();
457         amroot = (my_uid == 0);
458
459         /*
460          * Get the tty name. Entries will be logged indicating that the user
461          * tried to change to the named new user from the current terminal.
462          */
463         tty = ttyname (0);
464         if ((isatty (0) != 0) && (NULL != tty)) {
465 #ifndef USE_PAM
466                 is_console = console (tty);
467 #endif
468         } else {
469                 /*
470                  * Be more paranoid, like su from SimplePAMApps.  --marekm
471                  */
472                 if (!amroot) {
473                         fprintf (stderr,
474                                  _("%s: must be run from a terminal\n"), Prog);
475                         exit (1);
476                 }
477                 tty = "???";
478         }
479
480         /*
481          * The next argument must be either a user ID, or some flag to a
482          * subshell. Pretty sticky since you can't have an argument which
483          * doesn't start with a "-" unless you specify the new user name.
484          * Any remaining arguments will be passed to the user's login shell.
485          */
486         if ((optind < argc) && ('-' != argv[optind][0])) {
487                 STRFCPY (name, argv[optind++]); /* use this login id */
488                 if ((optind < argc) && (strcmp (argv[optind], "--") == 0)) {
489                         optind++;
490                 }
491         }
492         if ('\0' == name[0]) {          /* use default user */
493                 struct passwd *root_pw = getpwnam ("root");
494                 if ((NULL != root_pw) && (0 == root_pw->pw_uid)) {
495                         (void) strcpy (name, "root");
496                 } else {
497                         root_pw = getpwuid (0);
498                         if (NULL == root_pw) {
499                                 SYSLOG ((LOG_CRIT, "There is no UID 0 user."));
500                                 su_failure (tty);
501                         }
502                         (void) strcpy (name, root_pw->pw_name);
503                 }
504         }
505
506         doshell = (argc == optind);     /* any arguments remaining? */
507         if (NULL != command) {
508                 doshell = false;
509         }
510
511         /*
512          * Get the user's real name. The current UID is used to determine
513          * who has executed su. That user ID must exist.
514          */
515         pw = get_my_pwent ();
516         if (NULL == pw) {
517                 fprintf (stderr, _("%s: Cannot determine your user name.\n"),
518                          Prog);
519                 SYSLOG ((LOG_WARN, "Cannot determine the user name of the caller (UID %lu)",
520                          (unsigned long) my_uid));
521                 su_failure (tty);
522         }
523         STRFCPY (oldname, pw->pw_name);
524
525 #ifndef USE_PAM
526 #ifdef SU_ACCESS
527         /*
528          * Sort out the password of user calling su, in case needed later
529          * -- chris
530          */
531         spwd = getspnam (oldname); /* !USE_PAM, no need for xgetspnam */
532         if (NULL != spwd) {
533                 pw->pw_passwd = spwd->sp_pwdp;
534         }
535         oldpass = xstrdup (pw->pw_passwd);
536 #endif                          /* SU_ACCESS */
537
538 #else                           /* USE_PAM */
539         ret = pam_start ("su", name, &conv, &pamh);
540         if (PAM_SUCCESS != ret) {
541                 SYSLOG ((LOG_ERR, "pam_start: error %d", ret);
542                         fprintf (stderr, _("%s: pam_start: error %d\n"),
543                                  Prog, ret));
544                 exit (1);
545         }
546
547         ret = pam_set_item (pamh, PAM_TTY, (const void *) tty);
548         if (PAM_SUCCESS == ret) {
549                 ret = pam_set_item (pamh, PAM_RUSER, (const void *) oldname);
550         }
551         if (PAM_SUCCESS != ret) {
552                 SYSLOG ((LOG_ERR, "pam_set_item: %s",
553                          pam_strerror (pamh, ret)));
554                 fprintf (stderr, _("%s: %s\n"), Prog, pam_strerror (pamh, ret));
555                 pam_end (pamh, ret);
556                 exit (1);
557         }
558 #endif                          /* USE_PAM */
559
560       top:
561         /*
562          * This is the common point for validating a user whose name is
563          * known. It will be reached either by normal processing, or if the
564          * user is to be logged into a subsystem root.
565          *
566          * The password file entries for the user is gotten and the account
567          * validated.
568          */
569         pw = xgetpwnam (name);
570         if (NULL == pw) {
571                 (void) fprintf (stderr, _("Unknown id: %s\n"), name);
572                 closelog ();
573                 exit (1);
574         }
575 #ifndef USE_PAM
576         spwd = NULL;
577         if (strcmp (pw->pw_passwd, SHADOW_PASSWD_STRING) == 0) {
578                 spwd = getspnam (name); /* !USE_PAM, no need for xgetspnam */
579                 if (NULL != spwd) {
580                         pw->pw_passwd = spwd->sp_pwdp;
581                 }
582         }
583 #endif                          /* !USE_PAM */
584         pwent = *pw;
585
586         /* If su is not called by root, and the target user has a restricted
587          * shell, the environment must be changed.
588          */
589         change_environment |= (restricted_shell (pwent.pw_shell) && !amroot);
590
591         /*
592          * If a new login is being set up, the old environment will be
593          * ignored and a new one created later on.
594          * (note: in the case of a subsystem, the shell will be restricted,
595          *        and this won't be executed on the first pass)
596          */
597         if (change_environment && fakelogin) {
598                 /*
599                  * The terminal type will be left alone if it is present in
600                  * the environment already.
601                  */
602                 cp = getenv ("TERM");
603                 if (NULL != cp) {
604                         addenv ("TERM", cp);
605                 }
606
607                 /*
608                  * For some terminals COLORTERM seems to be the only way
609                  * for checking for that specific terminal. For instance,
610                  * gnome-terminal sets its TERM as "xterm" but its
611                  * COLORTERM as "gnome-terminal". The COLORTERM variable
612                  * is also of use when running GNU screen since it sets
613                  * TERM to "screen" but doesn't touch COLORTERM.
614                  */
615                 cp = getenv ("COLORTERM");
616                 if (NULL != cp) {
617                         addenv ("COLORTERM", cp);
618                 }
619
620 #ifndef USE_PAM
621                 cp = getdef_str ("ENV_TZ");
622                 if (NULL != cp) {
623                         addenv (('/' == *cp) ? tz (cp) : cp, NULL);
624                 }
625
626                 /*
627                  * The clock frequency will be reset to the login value if required
628                  */
629                 cp = getdef_str ("ENV_HZ");
630                 if (NULL != cp) {
631                         addenv (cp, NULL);      /* set the default $HZ, if one */
632                 }
633 #endif                          /* !USE_PAM */
634
635                 /*
636                  * Also leave DISPLAY and XAUTHORITY if present, else
637                  * pam_xauth will not work.
638                  */
639                 cp = getenv ("DISPLAY");
640                 if (NULL != cp) {
641                         addenv ("DISPLAY", cp);
642                 }
643                 cp = getenv ("XAUTHORITY");
644                 if (NULL != cp) {
645                         addenv ("XAUTHORITY", cp);
646                 }
647         } else {
648                 while (NULL != *envp) {
649                         addenv (*envp, NULL);
650                         envp++;
651                 }
652         }
653
654 #ifndef USE_PAM
655         /*
656          * BSD systems only allow "wheel" to SU to root. USG systems don't,
657          * so we make this a configurable option.
658          */
659
660         /* The original Shadow 3.3.2 did this differently. Do it like BSD:
661          *
662          * - check for UID 0 instead of name "root" - there are systems with
663          *   several root accounts under different names,
664          *
665          * - check the contents of /etc/group instead of the current group
666          *   set (you must be listed as a member, GID 0 is not sufficient).
667          *
668          * In addition to this traditional feature, we now have complete su
669          * access control (allow, deny, no password, own password).  Thanks
670          * to Chris Evans <lady0110@sable.ox.ac.uk>.
671          */
672
673         if (!amroot) {
674                 if (   (0 == pwent.pw_uid)
675                     && getdef_bool ("SU_WHEEL_ONLY")
676                     && !iswheel (oldname)) {
677                         fprintf (stderr,
678                                  _("You are not authorized to su %s\n"), name);
679                         exit (1);
680                 }
681 #ifdef SU_ACCESS
682                 switch (check_su_auth (oldname, name)) {
683                 case 0: /* normal su, require target user's password */
684                         break;
685                 case 1: /* require no password */
686                         pwent.pw_passwd = "";   /* XXX warning: const */
687                         break;
688                 case 2: /* require own password */
689                         puts (_("(Enter your own password)"));
690                         pwent.pw_passwd = oldpass;
691                         break;
692                 default:        /* access denied (-1) or unexpected value */
693                         fprintf (stderr,
694                                  _("You are not authorized to su %s\n"), name);
695                         exit (1);
696                 }
697 #endif                          /* SU_ACCESS */
698         }
699 #endif                          /* !USE_PAM */
700
701         /* If the user do not want to change the environment,
702          * use the current SHELL.
703          * (unless another shell is required by the command line)
704          */
705         if ((NULL == shellstr) && !change_environment) {
706                 shellstr = getenv ("SHELL");
707         }
708         /* For users with non null UID, if this user has a restricted
709          * shell, the shell must be the one specified in /etc/passwd
710          */
711         if (   (NULL != shellstr)
712             && !amroot
713             && restricted_shell (pwent.pw_shell)) {
714                 shellstr = NULL;
715         }
716         /* If the shell is not set at this time, use the shell specified
717          * in /etc/passwd.
718          */
719         if (NULL == shellstr) {
720                 shellstr = (char *) strdup (pwent.pw_shell);
721         }
722
723         /*
724          * Set the default shell.
725          */
726         if ((NULL == shellstr) || ('\0' == shellstr[0])) {
727                 shellstr = SHELL;
728         }
729
730         (void) signal (SIGINT, SIG_IGN);
731         (void) signal (SIGQUIT, SIG_IGN);
732 #ifdef USE_PAM
733         ret = pam_authenticate (pamh, 0);
734         if (PAM_SUCCESS != ret) {
735                 SYSLOG ((LOG_ERR, "pam_authenticate: %s",
736                          pam_strerror (pamh, ret)));
737                 fprintf (stderr, _("%s: %s\n"), Prog, pam_strerror (pamh, ret));
738                 (void) pam_end (pamh, ret);
739                 su_failure (tty);
740         }
741
742         ret = pam_acct_mgmt (pamh, 0);
743         if (PAM_SUCCESS != ret) {
744                 if (amroot) {
745                         fprintf (stderr, _("%s: %s\n(Ignored)\n"), Prog,
746                                  pam_strerror (pamh, ret));
747                 } else if (PAM_NEW_AUTHTOK_REQD == ret) {
748                         ret = pam_chauthtok (pamh, PAM_CHANGE_EXPIRED_AUTHTOK);
749                         if (PAM_SUCCESS != ret) {
750                                 SYSLOG ((LOG_ERR, "pam_chauthtok: %s",
751                                          pam_strerror (pamh, ret)));
752                                 fprintf (stderr, _("%s: %s\n"), Prog,
753                                          pam_strerror (pamh, ret));
754                                 (void) pam_end (pamh, ret);
755                                 su_failure (tty);
756                         }
757                 } else {
758                         SYSLOG ((LOG_ERR, "pam_acct_mgmt: %s",
759                                  pam_strerror (pamh, ret)));
760                         fprintf (stderr, _("%s: %s\n"), Prog,
761                                  pam_strerror (pamh, ret));
762                         (void) pam_end (pamh, ret);
763                         su_failure (tty);
764                 }
765         }
766 #else                           /* !USE_PAM */
767         /*
768          * Set up a signal handler in case the user types QUIT.
769          */
770         die (0);
771         oldsig = signal (SIGQUIT, die);
772
773         /*
774          * See if the system defined authentication method is being used. 
775          * The first character of an administrator defined method is an '@'
776          * character.
777          */
778         if (!amroot && pw_auth (pwent.pw_passwd, name, PW_SU, (char *) 0)) {
779                 SYSLOG ((pwent.pw_uid ? LOG_NOTICE : LOG_WARN,
780                          "Authentication failed for %s", name));
781                 fprintf(stderr, _("%s: Authentication failure\n"), Prog);
782                 su_failure (tty);
783         }
784         (void) signal (SIGQUIT, oldsig);
785
786         /*
787          * Check to see if the account is expired. root gets to ignore any
788          * expired accounts, but normal users can't become a user with an
789          * expired password.
790          */
791         if (!amroot) {
792                 if (NULL == spwd) {
793                         spwd = pwd_to_spwd (&pwent);
794                 }
795
796                 if (expire (&pwent, spwd)) {
797                         /* !USE_PAM, no need for xgetpwnam */
798                         struct passwd *pwd = getpwnam (name);
799
800                         /* !USE_PAM, no need for xgetspnam */
801                         spwd = getspnam (name);
802                         if (NULL != pwd) {
803                                 pwent = *pwd;
804                         }
805                 }
806         }
807
808         /*
809          * Check to see if the account permits "su". root gets to ignore any
810          * restricted accounts, but normal users can't become a user if
811          * there is a "SU" entry in the /etc/porttime file denying access to
812          * the account.
813          */
814         if (!amroot) {
815                 if (!isttytime (pwent.pw_name, "SU", time ((time_t *) 0))) {
816                         SYSLOG (((0 != pwent.pw_uid) ? LOG_WARN : LOG_CRIT,
817                                  "SU by %s to restricted account %s",
818                                  oldname, name));
819                         fprintf(stderr,
820                                 _("%s: You are not authorized to su at that time\n"), Prog);
821                         su_failure (tty);
822                 }
823         }
824 #endif                          /* !USE_PAM */
825
826         (void) signal (SIGINT, SIG_DFL);
827         (void) signal (SIGQUIT, SIG_DFL);
828
829         cp = getdef_str ((pwent.pw_uid == 0) ? "ENV_SUPATH" : "ENV_PATH");
830         if (NULL == cp) {
831                 addenv ("PATH=/bin:/usr/bin", NULL);
832         } else if (strchr (cp, '=') != NULL) {
833                 addenv (cp, NULL);
834         } else {
835                 addenv ("PATH", cp);
836         }
837
838         if (getenv ("IFS") != NULL) {   /* don't export user IFS ... */
839                 addenv ("IFS= \t\n", NULL);     /* ... instead, set a safe IFS */
840         }
841
842         /*
843          * Even if --shell is specified, the subsystem login test is based on
844          * the shell specified in /etc/passwd (not the one specified with
845          * --shell, which will be the one executed in the chroot later).
846          */
847         if ('*' == pwent.pw_shell[0]) { /* subsystem root required */
848                 pwent.pw_shell++;       /* skip the '*' */
849                 subsystem (&pwent);     /* figure out what to execute */
850                 endpwent ();
851                 endspent ();
852                 goto top;
853         }
854
855         sulog (tty, true, oldname, name);       /* save SU information */
856         endpwent ();
857         endspent ();
858 #ifdef USE_SYSLOG
859         if (getdef_bool ("SYSLOG_SU_ENAB")) {
860                 SYSLOG ((LOG_INFO, "+ %s %s:%s", tty,
861                          ('\0' != oldname[0]) ? oldname : "???",
862                          ('\0' != name[0]) ? name : "???"));
863         }
864 #endif
865
866 #ifdef USE_PAM
867         /* set primary group id and supplementary groups */
868         if (setup_groups (&pwent) != 0) {
869                 pam_end (pamh, PAM_ABORT);
870                 exit (1);
871         }
872
873         /*
874          * pam_setcred() may do things like resource limits, console groups,
875          * and much more, depending on the configured modules
876          */
877         ret = pam_setcred (pamh, PAM_ESTABLISH_CRED);
878         if (PAM_SUCCESS != ret) {
879                 SYSLOG ((LOG_ERR, "pam_setcred: %s", pam_strerror (pamh, ret)));
880                 fprintf (stderr, _("%s: %s\n"), Prog, pam_strerror (pamh, ret));
881                 (void) pam_end (pamh, ret);
882                 exit (1);
883         }
884
885         ret = pam_open_session (pamh, 0);
886         if (PAM_SUCCESS != ret) {
887                 SYSLOG ((LOG_ERR, "pam_open_session: %s",
888                          pam_strerror (pamh, ret)));
889                 fprintf (stderr, _("%s: %s\n"), Prog, pam_strerror (pamh, ret));
890                 pam_setcred (pamh, PAM_DELETE_CRED);
891                 (void) pam_end (pamh, ret);
892                 exit (1);
893         }
894
895         if (change_environment) {
896                 /* we need to setup the environment *after* pam_open_session(),
897                  * else the UID is changed before stuff like pam_xauth could
898                  * run, and we cannot access /etc/shadow and co
899                  */
900                 environ = newenvp;      /* make new environment active */
901
902                 /* update environment with all pam set variables */
903                 envcp = pam_getenvlist (pamh);
904                 if (NULL != envcp) {
905                         while (NULL != *envcp) {
906                                 addenv (*envcp, NULL);
907                                 envcp++;
908                         }
909                 }
910         }
911
912         /* become the new user */
913         if (change_uid (&pwent) != 0) {
914                 pam_close_session (pamh, 0);
915                 pam_setcred (pamh, PAM_DELETE_CRED);
916                 (void) pam_end (pamh, PAM_ABORT);
917                 exit (1);
918         }
919 #else                           /* !USE_PAM */
920         environ = newenvp;      /* make new environment active */
921
922         /* no limits if su from root (unless su must fake login's behavior) */
923         if (!amroot || fakelogin) {
924                 setup_limits (&pwent);
925         }
926
927         if (setup_uid_gid (&pwent, is_console) != 0) {
928                 exit (1);
929         }
930 #endif                          /* !USE_PAM */
931
932         if (change_environment) {
933                 if (fakelogin) {
934                         pwent.pw_shell = shellstr;
935                         setup_env (&pwent);
936                 } else {
937                         addenv ("HOME", pwent.pw_dir);
938                         addenv ("USER", pwent.pw_name);
939                         addenv ("LOGNAME", pwent.pw_name);
940                         addenv ("SHELL", shellstr);
941                 }
942         }
943
944         /*
945          * This is a workaround for Linux libc bug/feature (?) - the
946          * /dev/log file descriptor is open without the close-on-exec flag
947          * and used to be passed to the new shell. There is "fcntl(LogFile,
948          * F_SETFD, 1)" in libc/misc/syslog.c, but it is commented out (at
949          * least in 5.4.33). Why?  --marekm
950          */
951         closelog ();
952
953         /*
954          * See if the user has extra arguments on the command line. In that
955          * case they will be provided to the new user's shell as arguments.
956          */
957         if (fakelogin) {
958                 char *arg0;
959
960                 cp = getdef_str ("SU_NAME");
961                 if (NULL == cp) {
962                         cp = Basename (shellstr);
963                 }
964
965                 arg0 = xmalloc (strlen (cp) + 2);
966                 arg0[0] = '-';
967                 strcpy (arg0 + 1, cp);
968                 cp = arg0;
969         } else {
970                 cp = Basename (shellstr);
971         }
972
973         if (!doshell) {
974                 /* Position argv to the remaining arguments */
975                 argv += optind;
976                 if (NULL != command) {
977                         argv -= 2;
978                         argv[0] = "-c";
979                         argv[1] = command;
980                 }
981                 /*
982                  * Use the shell and create an argv
983                  * with the rest of the command line included.
984                  */
985                 argv[-1] = shellstr;
986 #ifndef USE_PAM
987                 execve_shell (shellstr, &argv[-1], environ);
988                 err = errno;
989                 (void) fputs (_("No shell\n"), stderr);
990                 SYSLOG ((LOG_WARN, "Cannot execute %s", shellstr));
991                 closelog ();
992                 exit ((ENOENT == err) ? E_CMD_NOTFOUND : E_CMD_NOEXEC);
993 #else
994                 run_shell (shellstr, &argv[-1], false, environ); /* no return */
995 #endif
996         }
997 #ifndef USE_PAM
998         err = shell (shellstr, cp, environ);
999         exit ((ENOENT == err) ? E_CMD_NOTFOUND : E_CMD_NOEXEC);
1000 #else
1001         run_shell (shellstr, &cp, true, environ);
1002 #endif
1003         /* NOT REACHED */
1004         exit (1);
1005 }
1006