]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/login/login.c
This commit was generated by cvs2svn to compensate for changes in r147894,
[FreeBSD/FreeBSD.git] / usr.bin / login / login.c
1 /*-
2  * Copyright (c) 1980, 1987, 1988, 1991, 1993, 1994
3  *      The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 2002 Networks Associates Technologies, Inc.
5  * All rights reserved.
6  *
7  * Portions of this software were developed for the FreeBSD Project by
8  * ThinkSec AS and NAI Labs, the Security Research Division of Network
9  * Associates, Inc.  under DARPA/SPAWAR contract N66001-01-C-8035
10  * ("CBOSS"), as part of the DARPA CHATS research program.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *      This product includes software developed by the University of
23  *      California, Berkeley and its contributors.
24  * 4. Neither the name of the University nor the names of its contributors
25  *    may be used to endorse or promote products derived from this software
26  *    without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38  * SUCH DAMAGE.
39  */
40
41 #if 0
42 #ifndef lint
43 static char sccsid[] = "@(#)login.c     8.4 (Berkeley) 4/2/94";
44 #endif
45 #endif
46
47 #include <sys/cdefs.h>
48 __FBSDID("$FreeBSD$");
49
50 /*
51  * login [ name ]
52  * login -h hostname    (for telnetd, etc.)
53  * login -f name        (for pre-authenticated login: datakit, xterm, etc.)
54  */
55
56 #include <sys/copyright.h>
57 #include <sys/param.h>
58 #include <sys/file.h>
59 #include <sys/stat.h>
60 #include <sys/time.h>
61 #include <sys/resource.h>
62 #include <sys/wait.h>
63
64 #include <err.h>
65 #include <errno.h>
66 #include <grp.h>
67 #include <libutil.h>
68 #include <login_cap.h>
69 #include <pwd.h>
70 #include <setjmp.h>
71 #include <signal.h>
72 #include <stdio.h>
73 #include <stdlib.h>
74 #include <string.h>
75 #include <syslog.h>
76 #include <ttyent.h>
77 #include <unistd.h>
78
79 #include <security/pam_appl.h>
80 #include <security/openpam.h>
81
82 #include "login.h"
83 #include "pathnames.h"
84
85 static int               auth_pam(void);
86 static void              bail(int, int);
87 static int               export(const char *);
88 static void              export_pam_environment(void);
89 static int               motd(const char *);
90 static void              badlogin(char *);
91 static char             *getloginname(void);
92 static void              pam_syslog(const char *);
93 static void              pam_cleanup(void);
94 static void              refused(const char *, const char *, int);
95 static const char       *stypeof(char *);
96 static void              sigint(int);
97 static void              timedout(int);
98 static void              usage(void);
99
100 #define TTYGRPNAME              "tty"                   /* group to own ttys */
101 #define DEFAULT_BACKOFF         3
102 #define DEFAULT_RETRIES         10
103 #define DEFAULT_PROMPT          "login: "
104 #define DEFAULT_PASSWD_PROMPT   "Password:"
105 #define TERM_UNKNOWN            "su"
106 #define DEFAULT_WARN            (2L * 7L * 86400L)      /* Two weeks */
107 #define NO_SLEEP_EXIT           0
108 #define SLEEP_EXIT              5
109
110 /*
111  * This bounds the time given to login.  Not a define so it can
112  * be patched on machines where it's too small.
113  */
114 static u_int            timeout = 300;
115
116 /* Buffer for signal handling of timeout */
117 static jmp_buf           timeout_buf;
118
119 struct passwd           *pwd;
120 static int               failures;
121
122 static char             *envinit[1];    /* empty environment list */
123
124 /*
125  * Command line flags and arguments
126  */
127 static int               fflag;         /* -f: do not perform authentication */
128 static int               hflag;         /* -h: login from remote host */
129 static char             *hostname;      /* hostname from command line */
130 static int               pflag;         /* -p: preserve environment */
131
132 /*
133  * User name
134  */
135 static char             *username;      /* user name */
136 static char             *olduser;       /* previous user name */
137
138 /*
139  * Prompts
140  */
141 static char              default_prompt[] = DEFAULT_PROMPT;
142 static const char       *prompt;
143 static char              default_passwd_prompt[] = DEFAULT_PASSWD_PROMPT;
144 static const char       *passwd_prompt;
145
146 static char             *tty;
147
148 /*
149  * PAM data
150  */
151 static pam_handle_t     *pamh = NULL;
152 static struct pam_conv   pamc = { openpam_ttyconv, NULL };
153 static int               pam_err;
154 static int               pam_silent = PAM_SILENT;
155 static int               pam_cred_established;
156 static int               pam_session_established;
157
158 int
159 main(int argc, char *argv[])
160 {
161         struct group *gr;
162         struct stat st;
163         int retries, backoff;
164         int ask, ch, cnt, quietlog, rootlogin, rval;
165         uid_t uid, euid;
166         gid_t egid;
167         char *term;
168         char *p, *ttyn;
169         char tname[sizeof(_PATH_TTY) + 10];
170         char *arg0;
171         const char *tp;
172         const char *shell = NULL;
173         login_cap_t *lc = NULL;
174         login_cap_t *lc_user = NULL;
175         pid_t pid;
176
177         (void)signal(SIGQUIT, SIG_IGN);
178         (void)signal(SIGINT, SIG_IGN);
179         (void)signal(SIGHUP, SIG_IGN);
180         if (setjmp(timeout_buf)) {
181                 if (failures)
182                         badlogin(username);
183                 (void)fprintf(stderr, "Login timed out after %d seconds\n",
184                     timeout);
185                 bail(NO_SLEEP_EXIT, 0);
186         }
187         (void)signal(SIGALRM, timedout);
188         (void)alarm(timeout);
189         (void)setpriority(PRIO_PROCESS, 0, 0);
190
191         openlog("login", LOG_ODELAY, LOG_AUTH);
192
193         uid = getuid();
194         euid = geteuid();
195         egid = getegid();
196
197         while ((ch = getopt(argc, argv, "fh:p")) != -1)
198                 switch (ch) {
199                 case 'f':
200                         fflag = 1;
201                         break;
202                 case 'h':
203                         if (uid != 0)
204                                 errx(1, "-h option: %s", strerror(EPERM));
205                         if (strlen(optarg) >= MAXHOSTNAMELEN)
206                                 errx(1, "-h option: %s: exceeds maximum "
207                                     "hostname size", optarg);
208                         hflag = 1;
209                         hostname = optarg;
210                         break;
211                 case 'p':
212                         pflag = 1;
213                         break;
214                 case '?':
215                 default:
216                         if (uid == 0)
217                                 syslog(LOG_ERR, "invalid flag %c", ch);
218                         usage();
219                 }
220         argc -= optind;
221         argv += optind;
222
223         if (argc > 0) {
224                 username = strdup(*argv);
225                 if (username == NULL)
226                         err(1, "strdup()");
227                 ask = 0;
228         } else {
229                 ask = 1;
230         }
231
232         setproctitle("-%s", getprogname());
233
234         for (cnt = getdtablesize(); cnt > 2; cnt--)
235                 (void)close(cnt);
236
237         /*
238          * Get current TTY
239          */
240         ttyn = ttyname(STDIN_FILENO);
241         if (ttyn == NULL || *ttyn == '\0') {
242                 (void)snprintf(tname, sizeof(tname), "%s??", _PATH_TTY);
243                 ttyn = tname;
244         }
245         if ((tty = strrchr(ttyn, '/')) != NULL)
246                 ++tty;
247         else
248                 tty = ttyn;
249
250         /*
251          * Get "login-retries" & "login-backoff" from default class
252          */
253         lc = login_getclass(NULL);
254         prompt = login_getcapstr(lc, "login_prompt",
255             default_prompt, default_prompt);
256         passwd_prompt = login_getcapstr(lc, "passwd_prompt",
257             default_passwd_prompt, default_passwd_prompt);
258         retries = login_getcapnum(lc, "login-retries",
259             DEFAULT_RETRIES, DEFAULT_RETRIES);
260         backoff = login_getcapnum(lc, "login-backoff",
261             DEFAULT_BACKOFF, DEFAULT_BACKOFF);
262         login_close(lc);
263         lc = NULL;
264
265         /*
266          * Try to authenticate the user until we succeed or time out.
267          */
268         for (cnt = 0;; ask = 1) {
269                 if (ask) {
270                         fflag = 0;
271                         if (olduser != NULL)
272                                 free(olduser);
273                         olduser = username;
274                         username = getloginname();
275                 }
276                 rootlogin = 0;
277
278                 /*
279                  * Note if trying multiple user names; log failures for
280                  * previous user name, but don't bother logging one failure
281                  * for nonexistent name (mistyped username).
282                  */
283                 if (failures && strcmp(olduser, username) != 0) {
284                         if (failures > (pwd ? 0 : 1))
285                                 badlogin(olduser);
286                 }
287
288                 /*
289                  * Load the PAM policy and set some variables
290                  */
291                 pam_err = pam_start("login", username, &pamc, &pamh);
292                 if (pam_err != PAM_SUCCESS) {
293                         pam_syslog("pam_start()");
294                         bail(NO_SLEEP_EXIT, 1);
295                 }
296                 pam_err = pam_set_item(pamh, PAM_TTY, tty);
297                 if (pam_err != PAM_SUCCESS) {
298                         pam_syslog("pam_set_item(PAM_TTY)");
299                         bail(NO_SLEEP_EXIT, 1);
300                 }
301                 pam_err = pam_set_item(pamh, PAM_RHOST, hostname);
302                 if (pam_err != PAM_SUCCESS) {
303                         pam_syslog("pam_set_item(PAM_RHOST)");
304                         bail(NO_SLEEP_EXIT, 1);
305                 }
306
307                 pwd = getpwnam(username);
308                 if (pwd != NULL && pwd->pw_uid == 0)
309                         rootlogin = 1;
310
311                 /*
312                  * If the -f option was specified and the caller is
313                  * root or the caller isn't changing their uid, don't
314                  * authenticate.
315                  */
316                 if (pwd != NULL && fflag &&
317                     (uid == (uid_t)0 || uid == (uid_t)pwd->pw_uid)) {
318                         /* already authenticated */
319                         rval = 0;
320                 } else {
321                         fflag = 0;
322                         (void)setpriority(PRIO_PROCESS, 0, -4);
323                         rval = auth_pam();
324                         (void)setpriority(PRIO_PROCESS, 0, 0);
325                 }
326
327                 if (pwd && rval == 0)
328                         break;
329
330                 pam_cleanup();
331
332                 (void)printf("Login incorrect\n");
333                 failures++;
334
335                 /*
336                  * Allow up to 'retry' (10) attempts, but start
337                  * backing off after 'backoff' (3) attempts.
338                  */
339                 if (++cnt > backoff) {
340                         if (cnt >= retries) {
341                                 badlogin(username);
342                                 bail(SLEEP_EXIT, 1);
343                         }
344                         sleep((u_int)((cnt - backoff) * 5));
345                 }
346         }
347
348         /* committed to login -- turn off timeout */
349         (void)alarm((u_int)0);
350         (void)signal(SIGHUP, SIG_DFL);
351
352         endpwent();
353
354         /*
355          * Establish the login class.
356          */
357         lc = login_getpwclass(pwd);
358         lc_user = login_getuserclass(pwd);
359
360         if (!(quietlog = login_getcapbool(lc_user, "hushlogin", 0)))
361                 quietlog = login_getcapbool(lc, "hushlogin", 0);
362
363         /*
364          * Switching needed for NFS with root access disabled.
365          *
366          * XXX: This change fails to modify the additional groups for the
367          * process, and as such, may restrict rights normally granted
368          * through those groups.
369          */
370         (void)setegid(pwd->pw_gid);
371         (void)seteuid(rootlogin ? 0 : pwd->pw_uid);
372         if (!*pwd->pw_dir || chdir(pwd->pw_dir) < 0) {
373                 if (login_getcapbool(lc, "requirehome", 0))
374                         refused("Home directory not available", "HOMEDIR", 1);
375                 if (chdir("/") < 0)
376                         refused("Cannot find root directory", "ROOTDIR", 1);
377                 if (!quietlog || *pwd->pw_dir)
378                         printf("No home directory.\nLogging in with home = \"/\".\n");
379                 pwd->pw_dir = strdup("/");
380                 if (pwd->pw_dir == NULL) {
381                         syslog(LOG_NOTICE, "strdup(): %m");
382                         bail(SLEEP_EXIT, 1);
383                 }
384         }
385         (void)seteuid(euid);
386         (void)setegid(egid);
387         if (!quietlog) {
388                 quietlog = access(_PATH_HUSHLOGIN, F_OK) == 0;
389                 if (!quietlog)
390                         pam_silent = 0;
391         }
392
393         shell = login_getcapstr(lc, "shell", pwd->pw_shell, pwd->pw_shell);
394         if (*pwd->pw_shell == '\0')
395                 pwd->pw_shell = strdup(_PATH_BSHELL);
396         if (pwd->pw_shell == NULL) {
397                 syslog(LOG_NOTICE, "strdup(): %m");
398                 bail(SLEEP_EXIT, 1);
399         }
400         if (*shell == '\0')   /* Not overridden */
401                 shell = pwd->pw_shell;
402         if ((shell = strdup(shell)) == NULL) {
403                 syslog(LOG_NOTICE, "strdup(): %m");
404                 bail(SLEEP_EXIT, 1);
405         }
406
407         /*
408          * Set device protections, depending on what terminal the
409          * user is logged in. This feature is used on Suns to give
410          * console users better privacy.
411          */
412         login_fbtab(tty, pwd->pw_uid, pwd->pw_gid);
413
414         /*
415          * Clear flags of the tty.  None should be set, and when the
416          * user sets them otherwise, this can cause the chown to fail.
417          * Since it isn't clear that flags are useful on character
418          * devices, we just clear them.
419          *
420          * We don't log in the case of EOPNOTSUPP because dev might be
421          * on NFS, which doesn't support chflags.
422          *
423          * We don't log in the EROFS because that means that /dev is on
424          * a read only file system and we assume that the permissions there
425          * are sane.
426          */
427         if (ttyn != tname && chflags(ttyn, 0))
428                 if (errno != EOPNOTSUPP && errno != EROFS)
429                         syslog(LOG_ERR, "chflags(%s): %m", ttyn);
430         if (ttyn != tname && chown(ttyn, pwd->pw_uid,
431             (gr = getgrnam(TTYGRPNAME)) ? gr->gr_gid : pwd->pw_gid))
432                 if (errno != EROFS)
433                         syslog(LOG_ERR, "chown(%s): %m", ttyn);
434
435         /*
436          * Exclude cons/vt/ptys only, assume dialup otherwise
437          * TODO: Make dialup tty determination a library call
438          * for consistency (finger etc.)
439          */
440         if (hflag && isdialuptty(tty))
441                 syslog(LOG_INFO, "DIALUP %s, %s", tty, pwd->pw_name);
442
443 #ifdef LOGALL
444         /*
445          * Syslog each successful login, so we don't have to watch
446          * hundreds of wtmp or lastlogin files.
447          */
448         if (hflag)
449                 syslog(LOG_INFO, "login from %s on %s as %s",
450                        hostname, tty, pwd->pw_name);
451         else
452                 syslog(LOG_INFO, "login on %s as %s",
453                        tty, pwd->pw_name);
454 #endif
455
456         /*
457          * If fflag is on, assume caller/authenticator has logged root
458          * login.
459          */
460         if (rootlogin && fflag == 0) {
461                 if (hflag)
462                         syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s FROM %s",
463                             username, tty, hostname);
464                 else
465                         syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s",
466                             username, tty);
467         }
468
469         /*
470          * Destroy environment unless user has requested its
471          * preservation - but preserve TERM in all cases
472          */
473         term = getenv("TERM");
474         if (!pflag)
475                 environ = envinit;
476         if (term != NULL)
477                 setenv("TERM", term, 0);
478
479         /*
480          * PAM modules might add supplementary groups during pam_setcred().
481          */
482         if (setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETGROUP) != 0) {
483                 syslog(LOG_ERR, "setusercontext() failed - exiting");
484                 bail(NO_SLEEP_EXIT, 1);
485         }
486
487         pam_err = pam_setcred(pamh, pam_silent|PAM_ESTABLISH_CRED);
488         if (pam_err != PAM_SUCCESS) {
489                 pam_syslog("pam_setcred()");
490                 bail(NO_SLEEP_EXIT, 1);
491         }
492         pam_cred_established = 1;
493
494         pam_err = pam_open_session(pamh, pam_silent);
495         if (pam_err != PAM_SUCCESS) {
496                 pam_syslog("pam_open_session()");
497                 bail(NO_SLEEP_EXIT, 1);
498         }
499         pam_session_established = 1;
500
501         /*
502          * We must fork() before setuid() because we need to call
503          * pam_close_session() as root.
504          */
505         pid = fork();
506         if (pid < 0) {
507                 err(1, "fork");
508         } else if (pid != 0) {
509                 /*
510                  * Parent: wait for child to finish, then clean up
511                  * session.
512                  */
513                 int status;
514                 setproctitle("-%s [pam]", getprogname());
515                 waitpid(pid, &status, 0);
516                 bail(NO_SLEEP_EXIT, 0);
517         }
518
519         /*
520          * NOTICE: We are now in the child process!
521          */
522
523         /*
524          * Add any environment variables the PAM modules may have set.
525          */
526         export_pam_environment();
527
528         /*
529          * We're done with PAM now; our parent will deal with the rest.
530          */
531         pam_end(pamh, 0);
532         pamh = NULL;
533
534         /*
535          * We don't need to be root anymore, so set the login name and
536          * the UID.
537          */
538         if (setlogin(username) != 0) {
539                 syslog(LOG_ERR, "setlogin(%s): %m - exiting", username);
540                 bail(NO_SLEEP_EXIT, 1);
541         }
542         if (setusercontext(lc, pwd, pwd->pw_uid,
543             LOGIN_SETALL & ~(LOGIN_SETLOGIN|LOGIN_SETGROUP)) != 0) {
544                 syslog(LOG_ERR, "setusercontext() failed - exiting");
545                 exit(1);
546         }
547
548         (void)setenv("SHELL", pwd->pw_shell, 1);
549         (void)setenv("HOME", pwd->pw_dir, 1);
550         /* Overwrite "term" from login.conf(5) for any known TERM */
551         if (term == NULL && (tp = stypeof(tty)) != NULL)
552                 (void)setenv("TERM", tp, 1);
553         else
554                 (void)setenv("TERM", TERM_UNKNOWN, 0);
555         (void)setenv("LOGNAME", username, 1);
556         (void)setenv("USER", username, 1);
557         (void)setenv("PATH", rootlogin ? _PATH_STDPATH : _PATH_DEFPATH, 0);
558
559         if (!quietlog) {
560                 const char *cw;
561
562                 cw = login_getcapstr(lc, "copyright", NULL, NULL);
563                 if (cw == NULL || motd(cw) == -1)
564                         (void)printf("%s", copyright);
565
566                 (void)printf("\n");
567
568                 cw = login_getcapstr(lc, "welcome", NULL, NULL);
569                 if (cw != NULL && access(cw, F_OK) == 0)
570                         motd(cw);
571                 else
572                         motd(_PATH_MOTDFILE);
573
574                 if (login_getcapbool(lc_user, "nocheckmail", 0) == 0 &&
575                     login_getcapbool(lc, "nocheckmail", 0) == 0) {
576                         char *cx;
577
578                         /* $MAIL may have been set by class. */
579                         cx = getenv("MAIL");
580                         if (cx == NULL) {
581                                 asprintf(&cx, "%s/%s",
582                                     _PATH_MAILDIR, pwd->pw_name);
583                         }
584                         if (cx && stat(cx, &st) == 0 && st.st_size != 0)
585                                 (void)printf("You have %smail.\n",
586                                     (st.st_mtime > st.st_atime) ? "new " : "");
587                         if (getenv("MAIL") == NULL)
588                                 free(cx);
589                 }
590         }
591
592         login_close(lc_user);
593         login_close(lc);
594
595         (void)signal(SIGALRM, SIG_DFL);
596         (void)signal(SIGQUIT, SIG_DFL);
597         (void)signal(SIGINT, SIG_DFL);
598         (void)signal(SIGTSTP, SIG_IGN);
599
600         /*
601          * Login shells have a leading '-' in front of argv[0]
602          */
603         p = strrchr(pwd->pw_shell, '/');
604         if (asprintf(&arg0, "-%s", p ? p + 1 : pwd->pw_shell) >= MAXPATHLEN) {
605                 syslog(LOG_ERR, "user: %s: shell exceeds maximum pathname size",
606                     username);
607                 errx(1, "shell exceeds maximum pathname size");
608         } else if (arg0 == NULL) {
609                 err(1, "asprintf()");
610         }
611
612         execlp(shell, arg0, (char *)0);
613         err(1, "%s", shell);
614
615         /*
616          * That's it, folks!
617          */
618 }
619
620 /*
621  * Attempt to authenticate the user using PAM.  Returns 0 if the user is
622  * authenticated, or 1 if not authenticated.  If some sort of PAM system
623  * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
624  * function returns -1.  This can be used as an indication that we should
625  * fall back to a different authentication mechanism.
626  */
627 static int
628 auth_pam(void)
629 {
630         const char *tmpl_user;
631         const void *item;
632         int rval;
633
634         pam_err = pam_authenticate(pamh, pam_silent);
635         switch (pam_err) {
636
637         case PAM_SUCCESS:
638                 /*
639                  * With PAM we support the concept of a "template"
640                  * user.  The user enters a login name which is
641                  * authenticated by PAM, usually via a remote service
642                  * such as RADIUS or TACACS+.  If authentication
643                  * succeeds, a different but related "template" name
644                  * is used for setting the credentials, shell, and
645                  * home directory.  The name the user enters need only
646                  * exist on the remote authentication server, but the
647                  * template name must be present in the local password
648                  * database.
649                  *
650                  * This is supported by two various mechanisms in the
651                  * individual modules.  However, from the application's
652                  * point of view, the template user is always passed
653                  * back as a changed value of the PAM_USER item.
654                  */
655                 pam_err = pam_get_item(pamh, PAM_USER, &item);
656                 if (pam_err == PAM_SUCCESS) {
657                         tmpl_user = (const char *)item;
658                         if (strcmp(username, tmpl_user) != 0)
659                                 pwd = getpwnam(tmpl_user);
660                 } else {
661                         pam_syslog("pam_get_item(PAM_USER)");
662                 }
663                 rval = 0;
664                 break;
665
666         case PAM_AUTH_ERR:
667         case PAM_USER_UNKNOWN:
668         case PAM_MAXTRIES:
669                 rval = 1;
670                 break;
671
672         default:
673                 pam_syslog("pam_authenticate()");
674                 rval = -1;
675                 break;
676         }
677
678         if (rval == 0) {
679                 pam_err = pam_acct_mgmt(pamh, pam_silent);
680                 switch (pam_err) {
681                 case PAM_SUCCESS:
682                         break;
683                 case PAM_NEW_AUTHTOK_REQD:
684                         pam_err = pam_chauthtok(pamh,
685                             pam_silent|PAM_CHANGE_EXPIRED_AUTHTOK);
686                         if (pam_err != PAM_SUCCESS) {
687                                 pam_syslog("pam_chauthtok()");
688                                 rval = 1;
689                         }
690                         break;
691                 default:
692                         pam_syslog("pam_acct_mgmt()");
693                         rval = 1;
694                         break;
695                 }
696         }
697
698         if (rval != 0) {
699                 pam_end(pamh, pam_err);
700                 pamh = NULL;
701         }
702         return (rval);
703 }
704
705 /*
706  * Export any environment variables PAM modules may have set
707  */
708 static void
709 export_pam_environment()
710 {
711         char **pam_env;
712         char **pp;
713
714         pam_env = pam_getenvlist(pamh);
715         if (pam_env != NULL) {
716                 for (pp = pam_env; *pp != NULL; pp++) {
717                         (void)export(*pp);
718                         free(*pp);
719                 }
720         }
721 }
722
723 /*
724  * Perform sanity checks on an environment variable:
725  * - Make sure there is an '=' in the string.
726  * - Make sure the string doesn't run on too long.
727  * - Do not export certain variables.  This list was taken from the
728  *   Solaris pam_putenv(3) man page.
729  * Then export it.
730  */
731 static int
732 export(const char *s)
733 {
734         static const char *noexport[] = {
735                 "SHELL", "HOME", "LOGNAME", "MAIL", "CDPATH",
736                 "IFS", "PATH", NULL
737         };
738         const char **pp;
739         size_t n;
740
741         if (strlen(s) > 1024 || strchr(s, '=') == NULL)
742                 return (0);
743         if (strncmp(s, "LD_", 3) == 0)
744                 return (0);
745         for (pp = noexport; *pp != NULL; pp++) {
746                 n = strlen(*pp);
747                 if (s[n] == '=' && strncmp(s, *pp, n) == 0)
748                         return (0);
749         }
750         (void)putenv(s);
751         return (1);
752 }
753
754 static void
755 usage()
756 {
757
758         (void)fprintf(stderr, "usage: login [-fp] [-h hostname] [username]\n");
759         exit(1);
760 }
761
762 /*
763  * Prompt user and read login name from stdin.
764  */
765 static char *
766 getloginname()
767 {
768         char *nbuf, *p;
769         int ch;
770
771         nbuf = malloc(MAXLOGNAME);
772         if (nbuf == NULL)
773                 err(1, "malloc()");
774         do {
775                 (void)printf("%s", prompt);
776                 for (p = nbuf; (ch = getchar()) != '\n'; ) {
777                         if (ch == EOF) {
778                                 badlogin(username);
779                                 bail(NO_SLEEP_EXIT, 0);
780                         }
781                         if (p < nbuf + MAXLOGNAME - 1)
782                                 *p++ = ch;
783                 }
784         } while (p == nbuf);
785
786         *p = '\0';
787         if (nbuf[0] == '-') {
788                 pam_silent = 0;
789                 memmove(nbuf, nbuf + 1, strlen(nbuf));
790         } else {
791                 pam_silent = PAM_SILENT;
792         }
793         return nbuf;
794 }
795
796 /*
797  * SIGINT handler for motd().
798  */
799 static volatile int motdinterrupt;
800 static void
801 sigint(int signo __unused)
802 {
803         motdinterrupt = 1;
804 }
805
806 /*
807  * Display the contents of a file (such as /etc/motd).
808  */
809 static int
810 motd(const char *motdfile)
811 {
812         sig_t oldint;
813         FILE *f;
814         int ch;
815
816         if ((f = fopen(motdfile, "r")) == NULL)
817                 return (-1);
818         motdinterrupt = 0;
819         oldint = signal(SIGINT, sigint);
820         while ((ch = fgetc(f)) != EOF && !motdinterrupt)
821                 putchar(ch);
822         signal(SIGINT, oldint);
823         if (ch != EOF || ferror(f)) {
824                 fclose(f);
825                 return (-1);
826         }
827         fclose(f);
828         return (0);
829 }
830
831 /*
832  * SIGALRM handler, to enforce login prompt timeout.
833  *
834  * XXX This can potentially confuse the hell out of PAM.  We should
835  * XXX instead implement a conversation function that returns
836  * XXX PAM_CONV_ERR when interrupted by a signal, and have the signal
837  * XXX handler just set a flag.
838  */
839 static void
840 timedout(int signo __unused)
841 {
842
843         longjmp(timeout_buf, signo);
844 }
845
846 static void
847 badlogin(char *name)
848 {
849
850         if (failures == 0)
851                 return;
852         if (hflag) {
853                 syslog(LOG_NOTICE, "%d LOGIN FAILURE%s FROM %s",
854                     failures, failures > 1 ? "S" : "", hostname);
855                 syslog(LOG_AUTHPRIV|LOG_NOTICE,
856                     "%d LOGIN FAILURE%s FROM %s, %s",
857                     failures, failures > 1 ? "S" : "", hostname, name);
858         } else {
859                 syslog(LOG_NOTICE, "%d LOGIN FAILURE%s ON %s",
860                     failures, failures > 1 ? "S" : "", tty);
861                 syslog(LOG_AUTHPRIV|LOG_NOTICE,
862                     "%d LOGIN FAILURE%s ON %s, %s",
863                     failures, failures > 1 ? "S" : "", tty, name);
864         }
865         failures = 0;
866 }
867
868 const char *
869 stypeof(char *ttyid)
870 {
871         struct ttyent *t;
872
873         if (ttyid != NULL && *ttyid != '\0') {
874                 t = getttynam(ttyid);
875                 if (t != NULL && t->ty_type != NULL)
876                         return (t->ty_type);
877         }
878         return (NULL);
879 }
880
881 static void
882 refused(const char *msg, const char *rtype, int lout)
883 {
884
885         if (msg != NULL)
886             printf("%s.\n", msg);
887         if (hflag)
888                 syslog(LOG_NOTICE, "LOGIN %s REFUSED (%s) FROM %s ON TTY %s",
889                     pwd->pw_name, rtype, hostname, tty);
890         else
891                 syslog(LOG_NOTICE, "LOGIN %s REFUSED (%s) ON TTY %s",
892                     pwd->pw_name, rtype, tty);
893         if (lout)
894                 bail(SLEEP_EXIT, 1);
895 }
896
897 /*
898  * Log a PAM error
899  */
900 static void
901 pam_syslog(const char *msg)
902 {
903         syslog(LOG_ERR, "%s: %s", msg, pam_strerror(pamh, pam_err));
904 }
905
906 /*
907  * Shut down PAM
908  */
909 static void
910 pam_cleanup()
911 {
912
913         if (pamh != NULL) {
914                 if (pam_session_established) {
915                         pam_err = pam_close_session(pamh, 0);
916                         if (pam_err != PAM_SUCCESS)
917                                 pam_syslog("pam_close_session()");
918                 }
919                 pam_session_established = 0;
920                 if (pam_cred_established) {
921                         pam_err = pam_setcred(pamh, pam_silent|PAM_DELETE_CRED);
922                         if (pam_err != PAM_SUCCESS)
923                                 pam_syslog("pam_setcred()");
924                 }
925                 pam_cred_established = 0;
926                 pam_end(pamh, pam_err);
927                 pamh = NULL;
928         }
929 }
930
931 /*
932  * Exit, optionally after sleeping a few seconds
933  */
934 void
935 bail(int sec, int eval)
936 {
937
938         pam_cleanup();
939         (void)sleep(sec);
940         exit(eval);
941 }