xref: /freebsd/usr.bin/login/login.c (revision 8ad26684)
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 #ifndef NO_PAM
82 #include <security/pam_appl.h>
83 #include <security/pam_misc.h>
84 #endif
85 
86 #include "pathnames.h"
87 
88 /* wrapper for KAME-special getnameinfo() */
89 #ifndef NI_WITHSCOPEID
90 #define	NI_WITHSCOPEID	0
91 #endif
92 
93 void	 badlogin __P((char *));
94 void	 checknologin __P((void));
95 void	 dolastlog __P((int));
96 void	 getloginname __P((void));
97 void	 motd __P((char *));
98 int	 rootterm __P((char *));
99 void	 sigint __P((int));
100 void	 sleepexit __P((int));
101 void	 refused __P((char *,char *,int));
102 char	*stypeof __P((char *));
103 void	 timedout __P((int));
104 int	 login_access __P((char *, char *));
105 void     login_fbtab __P((char *, uid_t, gid_t));
106 
107 #ifndef NO_PAM
108 static int auth_pam __P((void));
109 #endif
110 static int auth_traditional __P((void));
111 extern void login __P((struct utmp *));
112 static void usage __P((void));
113 
114 #define	TTYGRPNAME	"tty"		/* name of group to own ttys */
115 #define	DEFAULT_BACKOFF	3
116 #define	DEFAULT_RETRIES	10
117 
118 /*
119  * This bounds the time given to login.  Not a define so it can
120  * be patched on machines where it's too small.
121  */
122 u_int	timeout = 300;
123 
124 /* Buffer for signal handling of timeout */
125 jmp_buf timeout_buf;
126 
127 struct	passwd *pwd;
128 int	failures;
129 char	*term, *envinit[1], *hostname, *username, *tty;
130 char    full_hostname[MAXHOSTNAMELEN];
131 
132 int
133 main(argc, argv)
134 	int argc;
135 	char *argv[];
136 {
137 	extern char **environ;
138 	struct group *gr;
139 	struct stat st;
140 	struct timeval tp;
141 	struct utmp utmp;
142 	int rootok, retries, backoff;
143 	int ask, ch, cnt, fflag, hflag, pflag, quietlog, rootlogin, rval;
144 	int changepass;
145 	time_t warntime;
146 	uid_t uid, euid;
147 	gid_t egid;
148 	char *p, *ttyn;
149 	char tbuf[MAXPATHLEN + 2];
150 	char tname[sizeof(_PATH_TTY) + 10];
151 	char *shell = NULL;
152 	login_cap_t *lc = NULL;
153 
154 	(void)signal(SIGQUIT, SIG_IGN);
155 	(void)signal(SIGINT, SIG_IGN);
156 	if (setjmp(timeout_buf)) {
157 		if (failures)
158 			badlogin(tbuf);
159 		(void)fprintf(stderr,
160 			      "Login timed out after %d seconds\n", timeout);
161 		exit(0);
162 	}
163 	(void)signal(SIGALRM, timedout);
164 	(void)alarm(timeout);
165 	(void)setpriority(PRIO_PROCESS, 0, 0);
166 
167 	openlog("login", LOG_ODELAY, LOG_AUTH);
168 
169 	/*
170 	 * -p is used by getty to tell login not to destroy the environment
171 	 * -f is used to skip a second login authentication
172 	 * -h is used by other servers to pass the name of the remote
173 	 *    host to login so that it may be placed in utmp and wtmp
174 	 */
175 	*full_hostname = '\0';
176 	term = NULL;
177 
178 	fflag = hflag = pflag = 0;
179 	uid = getuid();
180 	euid = geteuid();
181 	egid = getegid();
182 	while ((ch = getopt(argc, argv, "fh:p")) != -1)
183 		switch (ch) {
184 		case 'f':
185 			fflag = 1;
186 			break;
187 		case 'h':
188 			if (uid)
189 				errx(1, "-h option: %s", strerror(EPERM));
190 			hflag = 1;
191 			strncpy(full_hostname, optarg, sizeof(full_hostname)-1);
192 
193 			trimdomain(optarg, UT_HOSTSIZE);
194 
195 			if (strlen(optarg) > UT_HOSTSIZE) {
196 				struct addrinfo hints, *res;
197 				int ga_err;
198 
199 				memset(&hints, 0, sizeof(hints));
200 				hints.ai_family = AF_UNSPEC;
201 				ga_err = getaddrinfo(optarg, NULL, &hints,
202 						    &res);
203 				if (ga_err == 0) {
204 					char hostbuf[MAXHOSTNAMELEN];
205 
206 					getnameinfo(res->ai_addr,
207 						    res->ai_addrlen,
208 						    hostbuf,
209 						    sizeof(hostbuf), NULL, 0,
210 						    NI_NUMERICHOST|
211 						    NI_WITHSCOPEID);
212 					optarg = strdup(hostbuf);
213 				} else
214 					optarg = "invalid hostname";
215 				if (res != NULL)
216 					freeaddrinfo(res);
217 			}
218 			hostname = optarg;
219 			break;
220 		case 'p':
221 			pflag = 1;
222 			break;
223 		case '?':
224 		default:
225 			if (!uid)
226 				syslog(LOG_ERR, "invalid flag %c", ch);
227 			usage();
228 		}
229 	argc -= optind;
230 	argv += optind;
231 
232 	if (*argv) {
233 		username = *argv;
234 		ask = 0;
235 	} else
236 		ask = 1;
237 
238 	for (cnt = getdtablesize(); cnt > 2; cnt--)
239 		(void)close(cnt);
240 
241 	ttyn = ttyname(STDIN_FILENO);
242 	if (ttyn == NULL || *ttyn == '\0') {
243 		(void)snprintf(tname, sizeof(tname), "%s??", _PATH_TTY);
244 		ttyn = tname;
245 	}
246 	if ((tty = strrchr(ttyn, '/')) != NULL)
247 		++tty;
248 	else
249 		tty = ttyn;
250 
251 	/*
252 	 * Get "login-retries" & "login-backoff" from default class
253 	 */
254 	lc = login_getclass(NULL);
255 	retries = login_getcapnum(lc, "login-retries", DEFAULT_RETRIES, DEFAULT_RETRIES);
256 	backoff = login_getcapnum(lc, "login-backoff", DEFAULT_BACKOFF, DEFAULT_BACKOFF);
257 	login_close(lc);
258 	lc = NULL;
259 
260 	for (cnt = 0;; ask = 1) {
261 		if (ask) {
262 			fflag = 0;
263 			getloginname();
264 		}
265 		rootlogin = 0;
266 		rootok = rootterm(tty); /* Default (auth may change) */
267 
268 		if (strlen(username) > UT_NAMESIZE)
269 			username[UT_NAMESIZE] = '\0';
270 
271 		/*
272 		 * Note if trying multiple user names; log failures for
273 		 * previous user name, but don't bother logging one failure
274 		 * for nonexistent name (mistyped username).
275 		 */
276 		if (failures && strcmp(tbuf, username)) {
277 			if (failures > (pwd ? 0 : 1))
278 				badlogin(tbuf);
279 		}
280 		(void)strncpy(tbuf, username, sizeof tbuf-1);
281 		tbuf[sizeof tbuf-1] = '\0';
282 
283 		pwd = getpwnam(username);
284 
285 		/*
286 		 * if we have a valid account name, and it doesn't have a
287 		 * password, or the -f option was specified and the caller
288 		 * is root or the caller isn't changing their uid, don't
289 		 * authenticate.
290 		 */
291 		if (pwd != NULL) {
292 			if (pwd->pw_uid == 0)
293 				rootlogin = 1;
294 
295 			if (fflag && (uid == (uid_t)0 ||
296 				      uid == (uid_t)pwd->pw_uid)) {
297 				/* already authenticated */
298 				break;
299 			} else if (pwd->pw_passwd[0] == '\0') {
300 				if (!rootlogin || rootok) {
301 					/* pretend password okay */
302 					rval = 0;
303 					goto ttycheck;
304 				}
305 			}
306 		}
307 
308 		fflag = 0;
309 
310 		(void)setpriority(PRIO_PROCESS, 0, -4);
311 
312 #ifndef NO_PAM
313 		/*
314 		 * Try to authenticate using PAM.  If a PAM system error
315 		 * occurs, perhaps because of a botched configuration,
316 		 * then fall back to using traditional Unix authentication.
317 		 */
318 		if ((rval = auth_pam()) == -1)
319 #endif /* NO_PAM */
320 			rval = auth_traditional();
321 
322 		(void)setpriority(PRIO_PROCESS, 0, 0);
323 
324 #ifndef NO_PAM
325 		/*
326 		 * PAM authentication may have changed "pwd" to the
327 		 * entry for the template user.  Check again to see if
328 		 * this is a root login after all.
329 		 */
330 		if (pwd != NULL && pwd->pw_uid == 0)
331 			rootlogin = 1;
332 #endif /* NO_PAM */
333 
334 	ttycheck:
335 		/*
336 		 * If trying to log in as root without Kerberos,
337 		 * but with insecure terminal, refuse the login attempt.
338 		 */
339 		if (pwd && !rval) {
340 			if (rootlogin && !rootok)
341 				refused(NULL, "NOROOT", 0);
342 			else	/* valid password & authenticated */
343 				break;
344 		}
345 
346 		(void)printf("Login incorrect\n");
347 		failures++;
348 
349 		/*
350 		 * we allow up to 'retry' (10) tries,
351 		 * but after 'backoff' (3) we start backing off
352 		 */
353 		if (++cnt > backoff) {
354 			if (cnt >= retries) {
355 				badlogin(username);
356 				sleepexit(1);
357 			}
358 			sleep((u_int)((cnt - backoff) * 5));
359 		}
360 	}
361 
362 	/* committed to login -- turn off timeout */
363 	(void)alarm((u_int)0);
364 
365 	endpwent();
366 
367 	/*
368 	 * Establish the login class.
369 	 */
370 	lc = login_getpwclass(pwd);
371 
372 	/* if user not super-user, check for disabled logins */
373 	if (!rootlogin)
374 		auth_checknologin(lc);
375 
376 	quietlog = login_getcapbool(lc, "hushlogin", 0);
377 	/* Switching needed for NFS with root access disabled */
378 	(void)setegid(pwd->pw_gid);
379 	(void)seteuid(rootlogin ? 0 : pwd->pw_uid);
380 	if (!*pwd->pw_dir || chdir(pwd->pw_dir) < 0) {
381 		if (login_getcapbool(lc, "requirehome", 0))
382 			refused("Home directory not available", "HOMEDIR", 1);
383 		if (chdir("/") < 0)
384 			refused("Cannot find root directory", "ROOTDIR", 1);
385 		if (!quietlog || *pwd->pw_dir)
386 			printf("No home directory.\nLogging in with home = \"/\".\n");
387 		pwd->pw_dir = "/";
388 	}
389 	(void)seteuid(euid);
390 	(void)setegid(egid);
391 	if (!quietlog)
392 		quietlog = access(_PATH_HUSHLOGIN, F_OK) == 0;
393 
394 	if (pwd->pw_change || pwd->pw_expire)
395 		(void)gettimeofday(&tp, (struct timezone *)NULL);
396 
397 #define DEFAULT_WARN  (2L * 7L * 86400L)  /* Two weeks */
398 
399 	warntime = login_getcaptime(lc, "warnpassword",
400 				    DEFAULT_WARN, DEFAULT_WARN);
401 
402 	changepass=0;
403 	if (pwd->pw_change) {
404 		if (tp.tv_sec >= pwd->pw_change) {
405 			(void)printf("Sorry -- your password has expired.\n");
406 			changepass=1;
407 			syslog(LOG_INFO,
408 			       "%s Password expired - forcing change",
409 			       pwd->pw_name);
410 		} else if (pwd->pw_change - tp.tv_sec < warntime && !quietlog)
411 		    (void)printf("Warning: your password expires on %s",
412 				 ctime(&pwd->pw_change));
413 	}
414 
415 	warntime = login_getcaptime(lc, "warnexpire",
416 				    DEFAULT_WARN, DEFAULT_WARN);
417 
418 	if (pwd->pw_expire) {
419 		if (tp.tv_sec >= pwd->pw_expire) {
420 			refused("Sorry -- your account has expired",
421 				"EXPIRED", 1);
422 		} else if (pwd->pw_expire - tp.tv_sec < warntime && !quietlog)
423 		    (void)printf("Warning: your account expires on %s",
424 				 ctime(&pwd->pw_expire));
425 	}
426 
427 	if (lc != NULL) {
428 		if (hostname) {
429 			struct addrinfo hints, *res;
430 			int ga_err;
431 
432 			memset(&hints, 0, sizeof(hints));
433 			hints.ai_family = AF_UNSPEC;
434 			ga_err = getaddrinfo(full_hostname, NULL, &hints,
435 					     &res);
436 			if (ga_err == 0) {
437 				char hostbuf[MAXHOSTNAMELEN];
438 
439 				getnameinfo(res->ai_addr, res->ai_addrlen,
440 					    hostbuf, sizeof(hostbuf), NULL, 0,
441 					    NI_NUMERICHOST|NI_WITHSCOPEID);
442 				optarg = strdup(hostbuf);
443 			} else
444 				optarg = NULL;
445 			if (res != NULL)
446 				freeaddrinfo(res);
447 			if (!auth_hostok(lc, full_hostname, optarg))
448 				refused("Permission denied", "HOST", 1);
449 		}
450 
451 		if (!auth_ttyok(lc, tty))
452 			refused("Permission denied", "TTY", 1);
453 
454 		if (!auth_timeok(lc, time(NULL)))
455 			refused("Logins not available right now", "TIME", 1);
456 	}
457         shell=login_getcapstr(lc, "shell", pwd->pw_shell, pwd->pw_shell);
458 	if (*pwd->pw_shell == '\0')
459 		pwd->pw_shell = _PATH_BSHELL;
460 	if (*shell == '\0')   /* Not overridden */
461 		shell = pwd->pw_shell;
462 	if ((shell = strdup(shell)) == NULL) {
463 		syslog(LOG_NOTICE, "memory allocation error");
464 		sleepexit(1);
465 	}
466 
467 #ifdef LOGIN_ACCESS
468 	if (login_access(pwd->pw_name, hostname ? full_hostname : tty) == 0)
469 		refused("Permission denied", "ACCESS", 1);
470 #endif /* LOGIN_ACCESS */
471 
472 	/* Nothing else left to fail -- really log in. */
473 	memset((void *)&utmp, 0, sizeof(utmp));
474 	(void)time(&utmp.ut_time);
475 	(void)strncpy(utmp.ut_name, username, sizeof(utmp.ut_name));
476 	if (hostname)
477 		(void)strncpy(utmp.ut_host, hostname, sizeof(utmp.ut_host));
478 	(void)strncpy(utmp.ut_line, tty, sizeof(utmp.ut_line));
479 	login(&utmp);
480 
481 	dolastlog(quietlog);
482 
483 	/*
484 	 * Set device protections, depending on what terminal the
485 	 * user is logged in. This feature is used on Suns to give
486 	 * console users better privacy.
487 	 */
488 	login_fbtab(tty, pwd->pw_uid, pwd->pw_gid);
489 
490 	/*
491 	 * Clear flags of the tty.  None should be set, and when the
492 	 * user sets them otherwise, this can cause the chown to fail.
493 	 * Since it isn't clear that flags are useful on character
494 	 * devices, we just clear them.
495 	 */
496 	if (chflags(ttyn, 0) && errno != EOPNOTSUPP)
497 		syslog(LOG_ERR, "chmod(%s): %m", ttyn);
498 	if (chown(ttyn, pwd->pw_uid,
499 	    (gr = getgrnam(TTYGRPNAME)) ? gr->gr_gid : pwd->pw_gid))
500 		syslog(LOG_ERR, "chmod(%s): %m", ttyn);
501 
502 
503 	/*
504 	 * Preserve TERM if it happens to be already set.
505 	 */
506 	if ((term = getenv("TERM")) != NULL)
507 		term = strdup(term);
508 
509 	/*
510 	 * Exclude cons/vt/ptys only, assume dialup otherwise
511 	 * TODO: Make dialup tty determination a library call
512 	 * for consistency (finger etc.)
513 	 */
514 	if (hostname==NULL && isdialuptty(tty))
515 		syslog(LOG_INFO, "DIALUP %s, %s", tty, pwd->pw_name);
516 
517 #ifdef LOGALL
518 	/*
519 	 * Syslog each successful login, so we don't have to watch hundreds
520 	 * of wtmp or lastlogin files.
521 	 */
522 	if (hostname)
523 		syslog(LOG_INFO, "login from %s on %s as %s",
524 		       full_hostname, tty, pwd->pw_name);
525 	else
526 		syslog(LOG_INFO, "login on %s as %s",
527 		       tty, pwd->pw_name);
528 #endif
529 
530 	/*
531 	 * If fflag is on, assume caller/authenticator has logged root login.
532 	 */
533 	if (rootlogin && fflag == 0)
534 	{
535 		if (hostname)
536 			syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s FROM %s",
537 			       username, tty, full_hostname);
538 		else
539 			syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s",
540 			       username, tty);
541 	}
542 
543 	/*
544 	 * Destroy environment unless user has requested its preservation.
545 	 * We need to do this before setusercontext() because that may
546 	 * set or reset some environment variables.
547 	 */
548 	if (!pflag)
549 		environ = envinit;
550 
551 	/*
552 	 * We don't need to be root anymore, so
553 	 * set the user and session context
554 	 */
555 	if (setlogin(username) != 0) {
556                 syslog(LOG_ERR, "setlogin(%s): %m - exiting", username);
557 		exit(1);
558 	}
559 	if (setusercontext(lc, pwd, pwd->pw_uid,
560 	    LOGIN_SETALL & ~LOGIN_SETLOGIN) != 0) {
561                 syslog(LOG_ERR, "setusercontext() failed - exiting");
562 		exit(1);
563 	}
564 
565 	(void)setenv("SHELL", pwd->pw_shell, 1);
566 	(void)setenv("HOME", pwd->pw_dir, 1);
567 	if (term != NULL && *term != '\0')
568 		(void)setenv("TERM", term, 1);	/* Preset overrides */
569 	else {
570 		(void)setenv("TERM", stypeof(tty), 0);	/* Fallback doesn't */
571 	}
572 	(void)setenv("LOGNAME", username, 1);
573 	(void)setenv("USER", username, 1);
574 	(void)setenv("PATH", rootlogin ? _PATH_STDPATH : _PATH_DEFPATH, 0);
575 
576 	if (!quietlog) {
577 		char	*cw;
578 
579 		cw = login_getcapstr(lc, "copyright", NULL, NULL);
580 		if (cw != NULL && access(cw, F_OK) == 0)
581 			motd(cw);
582 		else
583 		    (void)printf("%s\n\t%s %s\n",
584 	"Copyright (c) 1980, 1983, 1986, 1988, 1990, 1991, 1993, 1994",
585 	"The Regents of the University of California. ",
586 	"All rights reserved.");
587 
588 		(void)printf("\n");
589 
590 		cw = login_getcapstr(lc, "welcome", NULL, NULL);
591 		if (cw == NULL || access(cw, F_OK) != 0)
592 			cw = _PATH_MOTDFILE;
593 		motd(cw);
594 
595 		cw = getenv("MAIL");	/* $MAIL may have been set by class */
596 		if (cw != NULL) {
597 			strncpy(tbuf, cw, sizeof(tbuf));
598 			tbuf[sizeof(tbuf)-1] = '\0';
599 		} else
600 			snprintf(tbuf, sizeof(tbuf), "%s/%s",
601 				 _PATH_MAILDIR, pwd->pw_name);
602 		if (stat(tbuf, &st) == 0 && st.st_size != 0)
603 			(void)printf("You have %smail.\n",
604 				     (st.st_mtime > st.st_atime) ? "new " : "");
605 	}
606 
607 	login_close(lc);
608 
609 	(void)signal(SIGALRM, SIG_DFL);
610 	(void)signal(SIGQUIT, SIG_DFL);
611 	(void)signal(SIGINT, SIG_DFL);
612 	(void)signal(SIGTSTP, SIG_IGN);
613 
614 	if (changepass) {
615 		if (system(_PATH_CHPASS) != 0)
616 			sleepexit(1);
617 	}
618 
619 	/*
620 	 * Login shells have a leading '-' in front of argv[0]
621 	 */
622 	tbuf[0] = '-';
623 	(void)strcpy(tbuf + 1, (p = strrchr(pwd->pw_shell, '/')) ? p + 1 : pwd->pw_shell);
624 
625 	execlp(shell, tbuf, 0);
626 	err(1, "%s", shell);
627 }
628 
629 static int
630 auth_traditional()
631 {
632 	int rval;
633 	char *p;
634 	char *ep;
635 	char *salt;
636 
637 	rval = 1;
638 	salt = pwd != NULL ? pwd->pw_passwd : "xx";
639 
640 	p = getpass("Password:");
641 	ep = crypt(p, salt);
642 
643 	if (pwd) {
644 		if (!p[0] && pwd->pw_passwd[0])
645 			ep = ":";
646 		if (strcmp(ep, pwd->pw_passwd) == 0)
647 			rval = 0;
648 	}
649 
650 	/* clear entered password */
651 	memset(p, 0, strlen(p));
652 	return rval;
653 }
654 
655 #ifndef NO_PAM
656 /*
657  * Attempt to authenticate the user using PAM.  Returns 0 if the user is
658  * authenticated, or 1 if not authenticated.  If some sort of PAM system
659  * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
660  * function returns -1.  This can be used as an indication that we should
661  * fall back to a different authentication mechanism.
662  */
663 static int
664 auth_pam()
665 {
666 	pam_handle_t *pamh = NULL;
667 	const char *tmpl_user;
668 	const void *item;
669 	int rval;
670 	int e;
671 	static struct pam_conv conv = { misc_conv, NULL };
672 
673 	if ((e = pam_start("login", username, &conv, &pamh)) != PAM_SUCCESS) {
674 		syslog(LOG_ERR, "pam_start: %s", pam_strerror(pamh, e));
675 		return -1;
676 	}
677 	if ((e = pam_set_item(pamh, PAM_TTY, tty)) != PAM_SUCCESS) {
678 		syslog(LOG_ERR, "pam_set_item(PAM_TTY): %s",
679 		    pam_strerror(pamh, e));
680 		return -1;
681 	}
682 	if (hostname != NULL &&
683 	    (e = pam_set_item(pamh, PAM_RHOST, full_hostname)) != PAM_SUCCESS) {
684 		syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
685 		    pam_strerror(pamh, e));
686 		return -1;
687 	}
688 	e = pam_authenticate(pamh, 0);
689 	switch (e) {
690 
691 	case PAM_SUCCESS:
692 		/*
693 		 * With PAM we support the concept of a "template"
694 		 * user.  The user enters a login name which is
695 		 * authenticated by PAM, usually via a remote service
696 		 * such as RADIUS or TACACS+.  If authentication
697 		 * succeeds, a different but related "template" name
698 		 * is used for setting the credentials, shell, and
699 		 * home directory.  The name the user enters need only
700 		 * exist on the remote authentication server, but the
701 		 * template name must be present in the local password
702 		 * database.
703 		 *
704 		 * This is supported by two various mechanisms in the
705 		 * individual modules.  However, from the application's
706 		 * point of view, the template user is always passed
707 		 * back as a changed value of the PAM_USER item.
708 		 */
709 		if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
710 		    PAM_SUCCESS) {
711 			tmpl_user = (const char *) item;
712 			if (strcmp(username, tmpl_user) != 0)
713 				pwd = getpwnam(tmpl_user);
714 		} else
715 			syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
716 			    pam_strerror(pamh, e));
717 		if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) !=
718 		    PAM_SUCCESS)
719 			syslog(LOG_ERR, "Couldn't establish credentials: %s",
720 			    pam_strerror(pamh, e));
721 		rval = 0;
722 		break;
723 
724 	case PAM_AUTH_ERR:
725 	case PAM_USER_UNKNOWN:
726 	case PAM_MAXTRIES:
727 		rval = 1;
728 		break;
729 
730 	default:
731 		syslog(LOG_ERR, "auth_pam: %s", pam_strerror(pamh, e));
732 		rval = -1;
733 		break;
734 	}
735 	if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
736 		syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
737 		rval = -1;
738 	}
739 	return rval;
740 }
741 #endif /* NO_PAM */
742 
743 static void
744 usage()
745 {
746 	(void)fprintf(stderr, "usage: login [-fp] [-h hostname] [username]\n");
747 	exit(1);
748 }
749 
750 /*
751  * Allow for authentication style and/or kerberos instance
752  * */
753 
754 #define	NBUFSIZ		UT_NAMESIZE + 64
755 
756 void
757 getloginname()
758 {
759 	int ch;
760 	char *p;
761 	static char nbuf[NBUFSIZ];
762 
763 	for (;;) {
764 		(void)printf("login: ");
765 		for (p = nbuf; (ch = getchar()) != '\n'; ) {
766 			if (ch == EOF) {
767 				badlogin(username);
768 				exit(0);
769 			}
770 			if (p < nbuf + (NBUFSIZ - 1))
771 				*p++ = ch;
772 		}
773 		if (p > nbuf) {
774 			if (nbuf[0] == '-')
775 				(void)fprintf(stderr,
776 				    "login names may not start with '-'.\n");
777 			else {
778 				*p = '\0';
779 				username = nbuf;
780 				break;
781 			}
782 		}
783 	}
784 }
785 
786 int
787 rootterm(ttyn)
788 	char *ttyn;
789 {
790 	struct ttyent *t;
791 
792 	return ((t = getttynam(ttyn)) && t->ty_status & TTY_SECURE);
793 }
794 
795 volatile int motdinterrupt;
796 
797 /* ARGSUSED */
798 void
799 sigint(signo)
800 	int signo;
801 {
802 	motdinterrupt = 1;
803 }
804 
805 void
806 motd(motdfile)
807 	char *motdfile;
808 {
809 	int fd, nchars;
810 	sig_t oldint;
811 	char tbuf[256];
812 
813 	if ((fd = open(motdfile, O_RDONLY, 0)) < 0)
814 		return;
815 	motdinterrupt = 0;
816 	oldint = signal(SIGINT, sigint);
817 	while ((nchars = read(fd, tbuf, sizeof(tbuf))) > 0 && !motdinterrupt)
818 		(void)write(fileno(stdout), tbuf, nchars);
819 	(void)signal(SIGINT, oldint);
820 	(void)close(fd);
821 }
822 
823 /* ARGSUSED */
824 void
825 timedout(signo)
826 	int signo;
827 {
828 	longjmp(timeout_buf, signo);
829 }
830 
831 
832 void
833 dolastlog(quiet)
834 	int quiet;
835 {
836 	struct lastlog ll;
837 	int fd;
838 
839 	if ((fd = open(_PATH_LASTLOG, O_RDWR, 0)) >= 0) {
840 		(void)lseek(fd, (off_t)pwd->pw_uid * sizeof(ll), L_SET);
841 		if (!quiet) {
842 			if (read(fd, (char *)&ll, sizeof(ll)) == sizeof(ll) &&
843 			    ll.ll_time != 0) {
844 				(void)printf("Last login: %.*s ",
845 				    24-5, (char *)ctime(&ll.ll_time));
846 				if (*ll.ll_host != '\0')
847 					(void)printf("from %.*s\n",
848 					    (int)sizeof(ll.ll_host),
849 					    ll.ll_host);
850 				else
851 					(void)printf("on %.*s\n",
852 					    (int)sizeof(ll.ll_line),
853 					    ll.ll_line);
854 			}
855 			(void)lseek(fd, (off_t)pwd->pw_uid * sizeof(ll), L_SET);
856 		}
857 		memset((void *)&ll, 0, sizeof(ll));
858 		(void)time(&ll.ll_time);
859 		(void)strncpy(ll.ll_line, tty, sizeof(ll.ll_line));
860 		if (hostname)
861 			(void)strncpy(ll.ll_host, hostname, sizeof(ll.ll_host));
862 		(void)write(fd, (char *)&ll, sizeof(ll));
863 		(void)close(fd);
864 	}
865 }
866 
867 void
868 badlogin(name)
869 	char *name;
870 {
871 
872 	if (failures == 0)
873 		return;
874 	if (hostname) {
875 		syslog(LOG_NOTICE, "%d LOGIN FAILURE%s FROM %s",
876 		    failures, failures > 1 ? "S" : "", full_hostname);
877 		syslog(LOG_AUTHPRIV|LOG_NOTICE,
878 		    "%d LOGIN FAILURE%s FROM %s, %s",
879 		    failures, failures > 1 ? "S" : "", full_hostname, name);
880 	} else {
881 		syslog(LOG_NOTICE, "%d LOGIN FAILURE%s ON %s",
882 		    failures, failures > 1 ? "S" : "", tty);
883 		syslog(LOG_AUTHPRIV|LOG_NOTICE,
884 		    "%d LOGIN FAILURE%s ON %s, %s",
885 		    failures, failures > 1 ? "S" : "", tty, name);
886 	}
887 	failures = 0;
888 }
889 
890 #undef	UNKNOWN
891 #define	UNKNOWN	"su"
892 
893 char *
894 stypeof(ttyid)
895 	char *ttyid;
896 {
897 
898 	struct ttyent *t;
899 
900 	return (ttyid && (t = getttynam(ttyid)) ? t->ty_type : UNKNOWN);
901 }
902 
903 void
904 refused(msg, rtype, lout)
905 	char *msg;
906 	char *rtype;
907 	int lout;
908 {
909 
910 	if (msg != NULL)
911 	    printf("%s.\n", msg);
912 	if (hostname)
913 		syslog(LOG_NOTICE, "LOGIN %s REFUSED (%s) FROM %s ON TTY %s",
914 		       pwd->pw_name, rtype, full_hostname, tty);
915 	else
916 		syslog(LOG_NOTICE, "LOGIN %s REFUSED (%s) ON TTY %s",
917 		       pwd->pw_name, rtype, tty);
918 	if (lout)
919 		sleepexit(1);
920 }
921 
922 void
923 sleepexit(eval)
924 	int eval;
925 {
926 
927 	(void)sleep(5);
928 	exit(eval);
929 }
930