]> CyberLeo.Net >> Repos - FreeBSD/releng/8.2.git/blob - release/picobsd/tinyware/login/pico-login.c
Copy stable/8 to releng/8.2 in preparation for FreeBSD-8.2 release.
[FreeBSD/releng/8.2.git] / release / picobsd / tinyware / login / pico-login.c
1 /*-
2  * Copyright (c) 1980, 1987, 1988, 1991, 1993, 1994
3  *      The Regents of the University of California.  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. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 #if 0
35 static char copyright[] =
36 "@(#) Copyright (c) 1980, 1987, 1988, 1991, 1993, 1994\n\
37         The Regents of the University of California.  All rights reserved.\n";
38 #endif
39
40 #ifndef lint
41 #if 0
42 static char sccsid[] = "@(#)login.c     8.4 (Berkeley) 4/2/94";
43 #endif
44 static const char rcsid[] =
45   "$FreeBSD$";
46 #endif /* not lint */
47
48 /*
49  * login [ name ]
50  * login -h hostname    (for telnetd, etc.)
51  * login -f name        (for pre-authenticated login: datakit, xterm, etc.)
52  */
53
54 #include <sys/copyright.h>
55 #include <sys/param.h>
56 #include <sys/stat.h>
57 #include <sys/socket.h>
58 #include <sys/time.h>
59 #include <sys/resource.h>
60 #include <sys/file.h>
61 #include <netinet/in.h>
62 #include <arpa/inet.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 <netdb.h>
70 #include <pwd.h>
71 #include <setjmp.h>
72 #include <signal.h>
73 #include <stdio.h>
74 #include <stdlib.h>
75 #include <string.h>
76 #include <syslog.h>
77 #include <ttyent.h>
78 #include <unistd.h>
79 #include <utmp.h>
80
81 #ifdef USE_PAM
82 #include <security/pam_appl.h>
83 #include <security/openpam.h>
84 #include <sys/wait.h>
85 #endif /* USE_PAM */
86
87 #include "pathnames.h"
88
89 void     badlogin(char *);
90 void     checknologin(void);
91 void     dolastlog(int);
92 void     getloginname(void);
93 void     motd(const char *);
94 int      rootterm(char *);
95 void     sigint(int);
96 void     sleepexit(int);
97 void     refused(char *,char *,int);
98 char    *stypeof(char *);
99 void     timedout(int);
100 int      login_access(char *, char *);
101 void     login_fbtab(char *, uid_t, gid_t);
102
103 #ifdef USE_PAM
104 static int auth_pam(void);
105 static int export_pam_environment(void);
106 static int ok_to_export(const char *);
107
108 static pam_handle_t *pamh = NULL;
109 static char **environ_pam;
110
111 #define PAM_END { \
112         if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS) \
113                 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e)); \
114         if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS) \
115                 syslog(LOG_ERR, "pam_close_session: %s", pam_strerror(pamh, e)); \
116         if ((e = pam_end(pamh, e)) != PAM_SUCCESS) \
117                 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e)); \
118 }
119 #endif
120
121 static int auth_traditional(void);
122 extern void login(struct utmp *);
123 static void usage(void);
124
125 #define TTYGRPNAME      "tty"           /* name of group to own ttys */
126 #define DEFAULT_BACKOFF 3
127 #define DEFAULT_RETRIES 10
128 #define DEFAULT_PROMPT          "login: "
129 #define DEFAULT_PASSWD_PROMPT   "Password:"
130
131 /*
132  * This bounds the time given to login.  Not a define so it can
133  * be patched on machines where it's too small.
134  */
135 u_int   timeout = 300;
136
137 /* Buffer for signal handling of timeout */
138 jmp_buf timeout_buf;
139
140 struct  passwd *pwd;
141 int     failures;
142 char    *term, *envinit[1], *hostname, *tty, *username;
143 const char *passwd_prompt, *prompt;
144 char    full_hostname[MAXHOSTNAMELEN];
145
146 int
147 main(argc, argv)
148         int argc;
149         char *argv[];
150 {
151         extern char **environ;
152         struct group *gr;
153         struct stat st;
154         struct timeval tp;
155         struct utmp utmp;
156         int rootok, retries, backoff;
157         int ask, ch, cnt, fflag, hflag, pflag, quietlog, rootlogin, rval;
158         int changepass;
159         time_t warntime;
160         uid_t uid, euid;
161         gid_t egid;
162         char *p, *ttyn;
163         char tbuf[MAXPATHLEN + 2];
164         char tname[sizeof(_PATH_TTY) + 10];
165         const char *shell = NULL;
166         login_cap_t *lc = NULL;
167 #ifdef USE_PAM
168         pid_t pid;
169         int e;
170 #endif /* USE_PAM */
171
172         (void)signal(SIGQUIT, SIG_IGN);
173         (void)signal(SIGINT, SIG_IGN);
174         (void)signal(SIGHUP, SIG_IGN);
175         if (setjmp(timeout_buf)) {
176                 if (failures)
177                         badlogin(tbuf);
178                 (void)fprintf(stderr, "Login timed out after %d seconds\n",
179                     timeout);
180                 exit(0);
181         }
182         (void)signal(SIGALRM, timedout);
183         (void)alarm(timeout);
184         (void)setpriority(PRIO_PROCESS, 0, 0);
185
186         openlog("login", LOG_ODELAY, LOG_AUTH);
187
188         /*
189          * -p is used by getty to tell login not to destroy the environment
190          * -f is used to skip a second login authentication
191          * -h is used by other servers to pass the name of the remote
192          *    host to login so that it may be placed in utmp and wtmp
193          */
194         *full_hostname = '\0';
195         term = NULL;
196
197         fflag = hflag = pflag = 0;
198         uid = getuid();
199         euid = geteuid();
200         egid = getegid();
201         while ((ch = getopt(argc, argv, "fh:p")) != -1)
202                 switch (ch) {
203                 case 'f':
204                         fflag = 1;
205                         break;
206                 case 'h':
207                         if (uid)
208                                 errx(1, "-h option: %s", strerror(EPERM));
209                         hflag = 1;
210                         if (strlcpy(full_hostname, optarg,
211                             sizeof(full_hostname)) >= sizeof(full_hostname))
212                                 errx(1, "-h option: %s: exceeds maximum "
213                                     "hostname size", optarg);
214
215                         trimdomain(optarg, UT_HOSTSIZE);
216
217                         if (strlen(optarg) > UT_HOSTSIZE) {
218                                 struct addrinfo hints, *res;
219                                 int ga_err;
220                                 
221                                 memset(&hints, 0, sizeof(hints));
222                                 hints.ai_family = AF_UNSPEC;
223                                 ga_err = getaddrinfo(optarg, NULL, &hints,
224                                     &res);
225                                 if (ga_err == 0) {
226                                         char hostbuf[MAXHOSTNAMELEN];
227
228                                         getnameinfo(res->ai_addr,
229                                             res->ai_addrlen,
230                                             hostbuf,
231                                             sizeof(hostbuf), NULL, 0,
232                                             NI_NUMERICHOST);
233                                         optarg = strdup(hostbuf);
234                                         if (optarg == NULL) {
235                                                 syslog(LOG_NOTICE,
236                                                     "strdup(): %m");
237                                                 sleepexit(1);
238                                         }
239                                 } else
240                                         optarg = "invalid hostname";
241                                 if (res != NULL)
242                                         freeaddrinfo(res);
243                         }
244                         hostname = optarg;
245                         break;
246                 case 'p':
247                         pflag = 1;
248                         break;
249                 case '?':
250                 default:
251                         if (!uid)
252                                 syslog(LOG_ERR, "invalid flag %c", ch);
253                         usage();
254                 }
255         argc -= optind;
256         argv += optind;
257
258         if (*argv) {
259                 username = *argv;
260                 ask = 0;
261         } else
262                 ask = 1;
263
264         for (cnt = getdtablesize(); cnt > 2; cnt--)
265                 (void)close(cnt);
266
267         ttyn = ttyname(STDIN_FILENO);
268         if (ttyn == NULL || *ttyn == '\0') {
269                 (void)snprintf(tname, sizeof(tname), "%s??", _PATH_TTY);
270                 ttyn = tname;
271         }
272         if ((tty = strrchr(ttyn, '/')) != NULL)
273                 ++tty;
274         else
275                 tty = ttyn;
276
277         /*
278          * Get "login-retries" & "login-backoff" from default class
279          */
280         lc = login_getclass(NULL);
281         prompt = login_getcapstr(lc, "login_prompt",
282             DEFAULT_PROMPT, DEFAULT_PROMPT);
283         passwd_prompt = login_getcapstr(lc, "passwd_prompt",
284             DEFAULT_PASSWD_PROMPT, DEFAULT_PASSWD_PROMPT);
285         retries = login_getcapnum(lc, "login-retries", DEFAULT_RETRIES,
286             DEFAULT_RETRIES);
287         backoff = login_getcapnum(lc, "login-backoff", DEFAULT_BACKOFF,
288             DEFAULT_BACKOFF);
289         login_close(lc);
290         lc = NULL;
291
292         for (cnt = 0;; ask = 1) {
293                 if (ask) {
294                         fflag = 0;
295                         getloginname();
296                 }
297                 rootlogin = 0;
298                 rootok = rootterm(tty); /* Default (auth may change) */
299
300                 if (strlen(username) > UT_NAMESIZE)
301                         username[UT_NAMESIZE] = '\0';
302
303                 /*
304                  * Note if trying multiple user names; log failures for
305                  * previous user name, but don't bother logging one failure
306                  * for nonexistent name (mistyped username).
307                  */
308                 if (failures && strcmp(tbuf, username)) {
309                         if (failures > (pwd ? 0 : 1))
310                                 badlogin(tbuf);
311                 }
312                 (void)strlcpy(tbuf, username, sizeof(tbuf));
313
314                 pwd = getpwnam(username);
315
316                 /*
317                  * if we have a valid account name, and it doesn't have a
318                  * password, or the -f option was specified and the caller
319                  * is root or the caller isn't changing their uid, don't
320                  * authenticate.
321                  */
322                 if (pwd != NULL) {
323                         if (pwd->pw_uid == 0)
324                                 rootlogin = 1;
325
326                         if (fflag && (uid == (uid_t)0 ||
327                             uid == (uid_t)pwd->pw_uid)) {
328                                 /* already authenticated */
329                                 break;
330                         } else if (pwd->pw_passwd[0] == '\0') {
331                                 if (!rootlogin || rootok) {
332                                         /* pretend password okay */
333                                         rval = 0;
334                                         goto ttycheck;
335                                 }
336                         }
337                 }
338
339                 fflag = 0;
340
341                 (void)setpriority(PRIO_PROCESS, 0, -4);
342
343 #ifdef USE_PAM
344                 /*
345                  * Try to authenticate using PAM.  If a PAM system error
346                  * occurs, perhaps because of a botched configuration,
347                  * then fall back to using traditional Unix authentication.
348                  */
349                 if ((rval = auth_pam()) == -1)
350 #endif /* USE_PAM */
351                         rval = auth_traditional();
352
353                 (void)setpriority(PRIO_PROCESS, 0, 0);
354
355 #ifdef USE_PAM
356                 /*
357                  * PAM authentication may have changed "pwd" to the
358                  * entry for the template user.  Check again to see if
359                  * this is a root login after all.
360                  */
361                 if (pwd != NULL && pwd->pw_uid == 0)
362                         rootlogin = 1;
363 #endif /* USE_PAM */
364
365         ttycheck:
366                 /*
367                  * If trying to log in as root without Kerberos,
368                  * but with insecure terminal, refuse the login attempt.
369                  */
370                 if (pwd && !rval) {
371                         if (rootlogin && !rootok)
372                                 refused(NULL, "NOROOT", 0);
373                         else    /* valid password & authenticated */
374                                 break;
375                 }
376
377                 (void)printf("Login incorrect\n");
378                 failures++;
379
380                 /*
381                  * we allow up to 'retry' (10) tries,
382                  * but after 'backoff' (3) we start backing off
383                  */
384                 if (++cnt > backoff) {
385                         if (cnt >= retries) {
386                                 badlogin(username);
387                                 sleepexit(1);
388                         }
389                         sleep((u_int)((cnt - backoff) * 5));
390                 }
391         }
392
393         /* committed to login -- turn off timeout */
394         (void)alarm((u_int)0);
395         (void)signal(SIGHUP, SIG_DFL);
396
397         endpwent();
398
399         /*
400          * Establish the login class.
401          */
402         lc = login_getpwclass(pwd);
403
404         /* if user not super-user, check for disabled logins */
405         if (!rootlogin)
406                 auth_checknologin(lc);
407
408         quietlog = login_getcapbool(lc, "hushlogin", 0);
409         /*
410          * Switching needed for NFS with root access disabled.
411          *
412          * XXX: This change fails to modify the additional groups for the
413          * process, and as such, may restrict rights normally granted
414          * through those groups.
415          */
416         (void)setegid(pwd->pw_gid);
417         (void)seteuid(rootlogin ? 0 : pwd->pw_uid);
418         if (!*pwd->pw_dir || chdir(pwd->pw_dir) < 0) {
419                 if (login_getcapbool(lc, "requirehome", 0))
420                         refused("Home directory not available", "HOMEDIR", 1);
421                 if (chdir("/") < 0) 
422                         refused("Cannot find root directory", "ROOTDIR", 1);
423                 if (!quietlog || *pwd->pw_dir)
424                         printf("No home directory.\nLogging in with home = \"/\".\n");
425                 pwd->pw_dir = "/";
426         }
427         (void)seteuid(euid);
428         (void)setegid(egid);
429         if (!quietlog)
430                 quietlog = access(_PATH_HUSHLOGIN, F_OK) == 0;
431
432         if (pwd->pw_change || pwd->pw_expire)
433                 (void)gettimeofday(&tp, (struct timezone *)NULL);
434
435 #define DEFAULT_WARN  (2L * 7L * 86400L)  /* Two weeks */
436
437         warntime = login_getcaptime(lc, "warnexpire", DEFAULT_WARN,
438             DEFAULT_WARN);
439
440         if (pwd->pw_expire) {
441                 if (tp.tv_sec >= pwd->pw_expire) {
442                         refused("Sorry -- your account has expired", "EXPIRED",
443                             1);
444                 } else if (pwd->pw_expire - tp.tv_sec < warntime && !quietlog)
445                         (void)printf("Warning: your account expires on %s",
446                             ctime(&pwd->pw_expire));
447         }
448
449         warntime = login_getcaptime(lc, "warnpassword", DEFAULT_WARN,
450             DEFAULT_WARN);
451
452         changepass = 0;
453         if (pwd->pw_change) {
454                 if (tp.tv_sec >= pwd->pw_change) {
455                         (void)printf("Sorry -- your password has expired.\n");
456                         changepass = 1;
457                         syslog(LOG_INFO, "%s Password expired - forcing change",
458                             pwd->pw_name);
459                 } else if (pwd->pw_change - tp.tv_sec < warntime && !quietlog)
460                         (void)printf("Warning: your password expires on %s",
461                             ctime(&pwd->pw_change));
462         }
463
464         if (lc != NULL) {
465                 if (hostname) {
466                         struct addrinfo hints, *res;
467                         int ga_err;
468
469                         memset(&hints, 0, sizeof(hints));
470                         hints.ai_family = AF_UNSPEC;
471                         ga_err = getaddrinfo(full_hostname, NULL, &hints,
472                                              &res);
473                         if (ga_err == 0) {
474                                 char hostbuf[MAXHOSTNAMELEN];
475
476                                 getnameinfo(res->ai_addr, res->ai_addrlen,
477                                     hostbuf, sizeof(hostbuf), NULL, 0,
478                                     NI_NUMERICHOST);
479                                 if ((optarg = strdup(hostbuf)) == NULL) {
480                                         syslog(LOG_NOTICE, "strdup(): %m");
481                                         sleepexit(1);
482                                 }
483                         } else
484                                 optarg = NULL;
485                         if (res != NULL)
486                                 freeaddrinfo(res);
487                         if (!auth_hostok(lc, full_hostname, optarg))
488                                 refused("Permission denied", "HOST", 1);
489                 }
490
491                 if (!auth_ttyok(lc, tty))
492                         refused("Permission denied", "TTY", 1);
493
494                 if (!auth_timeok(lc, time(NULL)))
495                         refused("Logins not available right now", "TIME", 1);
496         }
497         shell = login_getcapstr(lc, "shell", pwd->pw_shell, pwd->pw_shell);
498         if (*pwd->pw_shell == '\0')
499                 pwd->pw_shell = _PATH_BSHELL;
500         if (*shell == '\0')   /* Not overridden */
501                 shell = pwd->pw_shell;
502         if ((shell = strdup(shell)) == NULL) {
503                 syslog(LOG_NOTICE, "strdup(): %m");
504                 sleepexit(1);
505         }
506
507 #ifdef LOGIN_ACCESS
508         if (login_access(pwd->pw_name, hostname ? full_hostname : tty) == 0)
509                 refused("Permission denied", "ACCESS", 1);
510 #endif /* LOGIN_ACCESS */
511
512         /* Nothing else left to fail -- really log in. */
513         memset((void *)&utmp, 0, sizeof(utmp));
514         (void)time(&utmp.ut_time);
515         (void)strncpy(utmp.ut_name, username, sizeof(utmp.ut_name));
516         if (hostname)
517                 (void)strncpy(utmp.ut_host, hostname, sizeof(utmp.ut_host));
518         (void)strncpy(utmp.ut_line, tty, sizeof(utmp.ut_line));
519         login(&utmp);
520
521         dolastlog(quietlog);
522
523         /*
524          * Set device protections, depending on what terminal the
525          * user is logged in. This feature is used on Suns to give
526          * console users better privacy.
527          */
528         login_fbtab(tty, pwd->pw_uid, pwd->pw_gid);
529
530         /*
531          * Clear flags of the tty.  None should be set, and when the
532          * user sets them otherwise, this can cause the chown to fail.
533          * Since it isn't clear that flags are useful on character
534          * devices, we just clear them.
535          */
536         if (chflags(ttyn, 0) && errno != EOPNOTSUPP)
537                 syslog(LOG_ERR, "chflags(%s): %m", ttyn);
538         if (chown(ttyn, pwd->pw_uid,
539             (gr = getgrnam(TTYGRPNAME)) ? gr->gr_gid : pwd->pw_gid))
540                 syslog(LOG_ERR, "chown(%s): %m", ttyn);
541
542
543         /*
544          * Preserve TERM if it happens to be already set.
545          */
546         if ((term = getenv("TERM")) != NULL) {
547                 if ((term = strdup(term)) == NULL) {
548                         syslog(LOG_NOTICE,
549                             "strdup(): %m");
550                         sleepexit(1);
551                 }
552         }
553
554         /*
555          * Exclude cons/vt/ptys only, assume dialup otherwise
556          * TODO: Make dialup tty determination a library call
557          * for consistency (finger etc.)
558          */
559         if (hostname==NULL && isdialuptty(tty))
560                 syslog(LOG_INFO, "DIALUP %s, %s", tty, pwd->pw_name);
561
562 #ifdef LOGALL
563         /*
564          * Syslog each successful login, so we don't have to watch hundreds
565          * of wtmp or lastlogin files.
566          */
567         if (hostname)
568                 syslog(LOG_INFO, "login from %s on %s as %s",
569                        full_hostname, tty, pwd->pw_name);
570         else
571                 syslog(LOG_INFO, "login on %s as %s",
572                        tty, pwd->pw_name);
573 #endif
574
575         /*
576          * If fflag is on, assume caller/authenticator has logged root login.
577          */
578         if (rootlogin && fflag == 0)
579         {
580                 if (hostname)
581                         syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s FROM %s",
582                             username, tty, full_hostname);
583                 else
584                         syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s",
585                             username, tty);
586         }
587
588         /*
589          * Destroy environment unless user has requested its preservation.
590          * We need to do this before setusercontext() because that may
591          * set or reset some environment variables.
592          */
593         if (!pflag)
594                 environ = envinit;
595
596         /*
597          * PAM modules might add supplementary groups during pam_setcred().
598          */
599         if (setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETGROUP) != 0) {
600                 syslog(LOG_ERR, "setusercontext() failed - exiting");
601                 exit(1);
602         }
603
604 #ifdef USE_PAM
605         if (pamh) {
606                 if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
607                         syslog(LOG_ERR, "pam_open_session: %s",
608                             pam_strerror(pamh, e));
609                 } else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED))
610                     != PAM_SUCCESS) {
611                         syslog(LOG_ERR, "pam_setcred: %s",
612                             pam_strerror(pamh, e));
613                 }
614
615                 /*
616                  * Add any environmental variables that the
617                  * PAM modules may have set.
618                  * Call *after* opening session!
619                  */
620                 if (pamh) {
621                   environ_pam = pam_getenvlist(pamh);
622                   if (environ_pam)
623                         export_pam_environment();
624                 }
625
626                 /*
627                  * We must fork() before setuid() because we need to call
628                  * pam_close_session() as root.
629                  */
630                 pid = fork();
631                 if (pid < 0) {
632                         err(1, "fork");
633                         PAM_END;
634                         exit(0);
635                 } else if (pid) {
636                         /* parent - wait for child to finish, then cleanup
637                            session */
638                         wait(NULL);
639                         PAM_END;
640                         exit(0);
641                 } else {
642                         if ((e = pam_end(pamh, 0)) != PAM_SUCCESS)
643                                 syslog(LOG_ERR, "pam_end: %s",
644                                     pam_strerror(pamh, e));
645                 }
646         }
647 #endif /* USE_PAM */
648
649         /*
650          * We don't need to be root anymore, so
651          * set the user and session context
652          */
653         if (setlogin(username) != 0) {
654                 syslog(LOG_ERR, "setlogin(%s): %m - exiting", username);
655                 exit(1);
656         }
657         if (setusercontext(lc, pwd, pwd->pw_uid,
658             LOGIN_SETALL & ~(LOGIN_SETLOGIN|LOGIN_SETGROUP)) != 0) {
659                 syslog(LOG_ERR, "setusercontext() failed - exiting");
660                 exit(1);
661         }
662
663         (void)setenv("SHELL", pwd->pw_shell, 1);
664         (void)setenv("HOME", pwd->pw_dir, 1);
665         if (term != NULL && *term != '\0')
666                 (void)setenv("TERM", term, 1);          /* Preset overrides */
667         else {
668                 (void)setenv("TERM", stypeof(tty), 0);  /* Fallback doesn't */
669         }
670         (void)setenv("LOGNAME", username, 1);
671         (void)setenv("USER", username, 1);
672         (void)setenv("PATH", rootlogin ? _PATH_STDPATH : _PATH_DEFPATH, 0);
673
674         if (!quietlog) {
675                 const char *cw;
676
677                 cw = login_getcapstr(lc, "copyright", NULL, NULL);
678                 if (cw != NULL && access(cw, F_OK) == 0)
679                         motd(cw);
680                 else
681                     (void)printf("%s\n\t%s %s\n",
682         "Copyright (c) 1980, 1983, 1986, 1988, 1990, 1991, 1993, 1994",
683         "The Regents of the University of California. ",
684         "All rights reserved.");
685
686                 (void)printf("\n");
687
688                 cw = login_getcapstr(lc, "welcome", NULL, NULL);
689                 if (cw == NULL || access(cw, F_OK) != 0)
690                         cw = _PATH_MOTDFILE;
691                 motd(cw);
692
693                 cw = getenv("MAIL");    /* $MAIL may have been set by class */
694                 if (cw != NULL)
695                         strlcpy(tbuf, cw, sizeof(tbuf));
696                 else
697                         snprintf(tbuf, sizeof(tbuf), "%s/%s", _PATH_MAILDIR,
698                             pwd->pw_name);
699                 if (stat(tbuf, &st) == 0 && st.st_size != 0)
700                         (void)printf("You have %smail.\n",
701                             (st.st_mtime > st.st_atime) ? "new " : "");
702         }
703
704         login_close(lc);
705
706         (void)signal(SIGALRM, SIG_DFL);
707         (void)signal(SIGQUIT, SIG_DFL);
708         (void)signal(SIGINT, SIG_DFL);
709         (void)signal(SIGTSTP, SIG_IGN);
710
711         /*
712          * Login shells have a leading '-' in front of argv[0]
713          */
714         if (snprintf(tbuf, sizeof(tbuf), "-%s",
715             (p = strrchr(pwd->pw_shell, '/')) ? p + 1 : pwd->pw_shell) >=
716             sizeof(tbuf)) {
717                 syslog(LOG_ERR, "user: %s: shell exceeds maximum pathname size",
718                     username);
719                 errx(1, "shell exceeds maximum pathname size");
720         }
721
722         execlp(shell, tbuf, (char *)0);
723         err(1, "%s", shell);
724 }
725
726 static int
727 auth_traditional()
728 {
729         int rval;
730         char *p;
731         char *ep;
732         char *salt;
733
734         rval = 1;
735         salt = pwd != NULL ? pwd->pw_passwd : "xx";
736
737         p = getpass(passwd_prompt);
738         ep = crypt(p, salt);
739
740         if (pwd) {
741                 if (!p[0] && pwd->pw_passwd[0])
742                         ep = ":";
743                 if (strcmp(ep, pwd->pw_passwd) == 0)
744                         rval = 0;
745         }
746
747         /* clear entered password */
748         memset(p, 0, strlen(p));
749         return rval;
750 }
751
752 #ifdef USE_PAM
753 /*
754  * Attempt to authenticate the user using PAM.  Returns 0 if the user is
755  * authenticated, or 1 if not authenticated.  If some sort of PAM system
756  * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
757  * function returns -1.  This can be used as an indication that we should
758  * fall back to a different authentication mechanism.
759  */
760 static int
761 auth_pam()
762 {
763         const char *tmpl_user;
764         const void *item;
765         int rval;
766         int e;
767         static struct pam_conv conv = { openpam_ttyconv, NULL };
768
769         if ((e = pam_start("login", username, &conv, &pamh)) != PAM_SUCCESS) {
770                 syslog(LOG_ERR, "pam_start: %s", pam_strerror(pamh, e));
771                 return -1;
772         }
773         if ((e = pam_set_item(pamh, PAM_TTY, tty)) != PAM_SUCCESS) {
774                 syslog(LOG_ERR, "pam_set_item(PAM_TTY): %s",
775                     pam_strerror(pamh, e));
776                 return -1;
777         }
778         if (hostname != NULL &&
779             (e = pam_set_item(pamh, PAM_RHOST, full_hostname)) != PAM_SUCCESS) {
780                 syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
781                     pam_strerror(pamh, e));
782                 return -1;
783         }
784         e = pam_authenticate(pamh, 0);
785         switch (e) {
786
787         case PAM_SUCCESS:
788                 /*
789                  * With PAM we support the concept of a "template"
790                  * user.  The user enters a login name which is
791                  * authenticated by PAM, usually via a remote service
792                  * such as RADIUS or TACACS+.  If authentication
793                  * succeeds, a different but related "template" name
794                  * is used for setting the credentials, shell, and
795                  * home directory.  The name the user enters need only
796                  * exist on the remote authentication server, but the
797                  * template name must be present in the local password
798                  * database.
799                  *
800                  * This is supported by two various mechanisms in the
801                  * individual modules.  However, from the application's
802                  * point of view, the template user is always passed
803                  * back as a changed value of the PAM_USER item.
804                  */
805                 if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
806                     PAM_SUCCESS) {
807                         tmpl_user = (const char *) item;
808                         if (strcmp(username, tmpl_user) != 0)
809                                 pwd = getpwnam(tmpl_user);
810                 } else
811                         syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
812                             pam_strerror(pamh, e));
813                 rval = 0;
814                 break;
815
816         case PAM_AUTH_ERR:
817         case PAM_USER_UNKNOWN:
818         case PAM_MAXTRIES:
819                 rval = 1;
820                 break;
821
822         default:
823                 syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
824                 rval = -1;
825                 break;
826         }
827
828         if (rval == 0) {
829                 e = pam_acct_mgmt(pamh, 0);
830                 if (e == PAM_NEW_AUTHTOK_REQD) {
831                         e = pam_chauthtok(pamh, PAM_CHANGE_EXPIRED_AUTHTOK);
832                         if (e != PAM_SUCCESS) {
833                                 syslog(LOG_ERR, "pam_chauthtok: %s",
834                                     pam_strerror(pamh, e));
835                                 rval = 1;
836                         }
837                 } else if (e != PAM_SUCCESS) {
838                         rval = 1;
839                 }
840         }
841
842         if (rval != 0) {
843                 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
844                         syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
845                 }
846                 pamh = NULL;
847         }
848         return rval;
849 }
850
851 static int
852 export_pam_environment()
853 {
854         char    **pp;
855
856         for (pp = environ_pam; *pp != NULL; pp++) {
857                 if (ok_to_export(*pp))
858                         (void) putenv(*pp);
859                 free(*pp);
860         }
861         return PAM_SUCCESS;
862 }
863
864 /*
865  * Sanity checks on PAM environmental variables:
866  * - Make sure there is an '=' in the string.
867  * - Make sure the string doesn't run on too long.
868  * - Do not export certain variables.  This list was taken from the
869  *   Solaris pam_putenv(3) man page.
870  */
871 static int
872 ok_to_export(s)
873         const char *s;
874 {
875         static const char *noexport[] = {
876                 "SHELL", "HOME", "LOGNAME", "MAIL", "CDPATH",
877                 "IFS", "PATH", NULL
878         };
879         const char **pp;
880         size_t n;
881
882         if (strlen(s) > 1024 || strchr(s, '=') == NULL)
883                 return 0;
884         if (strncmp(s, "LD_", 3) == 0)
885                 return 0;
886         for (pp = noexport; *pp != NULL; pp++) {
887                 n = strlen(*pp);
888                 if (s[n] == '=' && strncmp(s, *pp, n) == 0)
889                         return 0;
890         }
891         return 1;
892 }
893 #endif /* USE_PAM */
894
895 static void
896 usage()
897 {
898
899         (void)fprintf(stderr, "usage: login [-fp] [-h hostname] [username]\n");
900         exit(1);
901 }
902
903 /*
904  * Allow for authentication style and/or kerberos instance
905  */
906
907 #define NBUFSIZ         UT_NAMESIZE + 64
908
909 void
910 getloginname()
911 {
912         int ch;
913         char *p;
914         static char nbuf[NBUFSIZ];
915
916         for (;;) {
917                 (void)printf("%s", prompt);
918                 for (p = nbuf; (ch = getchar()) != '\n'; ) {
919                         if (ch == EOF) {
920                                 badlogin(username);
921                                 exit(0);
922                         }
923                         if (p < nbuf + (NBUFSIZ - 1))
924                                 *p++ = ch;
925                 }
926                 if (p > nbuf) {
927                         if (nbuf[0] == '-')
928                                 (void)fprintf(stderr,
929                                     "login names may not start with '-'.\n");
930                         else {
931                                 *p = '\0';
932                                 username = nbuf;
933                                 break;
934                         }
935                 }
936         }
937 }
938
939 int
940 rootterm(ttyn)
941         char *ttyn;
942 {
943         struct ttyent *t;
944
945         return ((t = getttynam(ttyn)) && t->ty_status & TTY_SECURE);
946 }
947
948 volatile int motdinterrupt;
949
950 void
951 sigint(signo)
952         int signo __unused;
953 {
954         motdinterrupt = 1;
955 }
956
957 void
958 motd(motdfile)
959         const char *motdfile;
960 {
961         int fd, nchars;
962         sig_t oldint;
963         char tbuf[256];
964
965         if ((fd = open(motdfile, O_RDONLY, 0)) < 0)
966                 return;
967         motdinterrupt = 0;
968         oldint = signal(SIGINT, sigint);
969         while ((nchars = read(fd, tbuf, sizeof(tbuf))) > 0 && !motdinterrupt)
970                 (void)write(fileno(stdout), tbuf, nchars);
971         (void)signal(SIGINT, oldint);
972         (void)close(fd);
973 }
974
975 /* ARGSUSED */
976 void
977 timedout(signo)
978         int signo;
979 {
980
981         longjmp(timeout_buf, signo);
982 }
983
984
985 void
986 dolastlog(quiet)
987         int quiet;
988 {
989         struct lastlog ll;
990         int fd;
991
992         if ((fd = open(_PATH_LASTLOG, O_RDWR, 0)) >= 0) {
993                 (void)lseek(fd, (off_t)pwd->pw_uid * sizeof(ll), L_SET);
994                 if (!quiet) {
995                         if (read(fd, (char *)&ll, sizeof(ll)) == sizeof(ll) &&
996                             ll.ll_time != 0) {
997                                 (void)printf("Last login: %.*s ",
998                                     24-5, (char *)ctime(&ll.ll_time));
999                                 if (*ll.ll_host != '\0')
1000                                         (void)printf("from %.*s\n",
1001                                             (int)sizeof(ll.ll_host),
1002                                             ll.ll_host);
1003                                 else
1004                                         (void)printf("on %.*s\n",
1005                                             (int)sizeof(ll.ll_line),
1006                                             ll.ll_line);
1007                         }
1008                         (void)lseek(fd, (off_t)pwd->pw_uid * sizeof(ll), L_SET);
1009                 }
1010                 memset((void *)&ll, 0, sizeof(ll));
1011                 (void)time(&ll.ll_time);
1012                 (void)strncpy(ll.ll_line, tty, sizeof(ll.ll_line));
1013                 if (hostname)
1014                         (void)strncpy(ll.ll_host, hostname, sizeof(ll.ll_host));
1015                 (void)write(fd, (char *)&ll, sizeof(ll));
1016                 (void)close(fd);
1017         } else {
1018                 syslog(LOG_ERR, "cannot open %s: %m", _PATH_LASTLOG);
1019         }
1020 }
1021
1022 void
1023 badlogin(name)
1024         char *name;
1025 {
1026
1027         if (failures == 0)
1028                 return;
1029         if (hostname) {
1030                 syslog(LOG_NOTICE, "%d LOGIN FAILURE%s FROM %s",
1031                     failures, failures > 1 ? "S" : "", full_hostname);
1032                 syslog(LOG_AUTHPRIV|LOG_NOTICE,
1033                     "%d LOGIN FAILURE%s FROM %s, %s",
1034                     failures, failures > 1 ? "S" : "", full_hostname, name);
1035         } else {
1036                 syslog(LOG_NOTICE, "%d LOGIN FAILURE%s ON %s",
1037                     failures, failures > 1 ? "S" : "", tty);
1038                 syslog(LOG_AUTHPRIV|LOG_NOTICE,
1039                     "%d LOGIN FAILURE%s ON %s, %s",
1040                     failures, failures > 1 ? "S" : "", tty, name);
1041         }
1042         failures = 0;
1043 }
1044
1045 #undef  UNKNOWN
1046 #define UNKNOWN "su"
1047
1048 char *
1049 stypeof(ttyid)
1050         char *ttyid;
1051 {
1052         struct ttyent *t;
1053
1054         if (ttyid != NULL && *ttyid != '\0') {
1055                 t = getttynam(ttyid);
1056                 if (t != NULL && t->ty_type != NULL)
1057                         return (t->ty_type);
1058         }
1059         return (UNKNOWN);
1060 }
1061
1062 void
1063 refused(msg, rtype, lout)
1064         char *msg;
1065         char *rtype;
1066         int lout;
1067 {
1068
1069         if (msg != NULL)
1070             printf("%s.\n", msg);
1071         if (hostname)
1072                 syslog(LOG_NOTICE, "LOGIN %s REFUSED (%s) FROM %s ON TTY %s",
1073                     pwd->pw_name, rtype, full_hostname, tty);
1074         else
1075                 syslog(LOG_NOTICE, "LOGIN %s REFUSED (%s) ON TTY %s",
1076                     pwd->pw_name, rtype, tty);
1077         if (lout)
1078                 sleepexit(1);
1079 }
1080
1081 void
1082 sleepexit(eval)
1083         int eval;
1084 {
1085
1086         (void)sleep(5);
1087         exit(eval);
1088 }