xref: /freebsd/usr.bin/login/login.c (revision 9c9cb2bffed13b27c9a005d4bd45d8244572f692)
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 	"$Id$";
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/time.h>
58 #include <sys/resource.h>
59 #include <sys/file.h>
60 #include <netinet/in.h>
61 #include <arpa/inet.h>
62 
63 #include <err.h>
64 #include <errno.h>
65 #include <grp.h>
66 #include <netdb.h>
67 #include <pwd.h>
68 #include <setjmp.h>
69 #include <signal.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <string.h>
73 #include <syslog.h>
74 #include <ttyent.h>
75 #include <unistd.h>
76 #include <utmp.h>
77 
78 #ifdef LOGIN_CAP
79 #include <login_cap.h>
80 #else /* Undef AUTH as well */
81 #undef LOGIN_CAP_AUTH
82 #endif
83 
84 /*
85  * If LOGIN_CAP_AUTH is activated:
86  * kerberose & skey logins are runtime selected via login
87  * login_getstyle() and authentication types for login classes
88  * The actual login itself is handled via /usr/libexec/login_<style>
89  * Valid styles are determined by the auth-type=style,style entries
90  * in the login class.
91  */
92 #ifdef LOGIN_CAP_AUTH
93 #undef KERBEROS
94 #undef SKEY
95 #endif /* LOGIN_CAP_AUTH */
96 
97 #ifdef	SKEY
98 #include <skey.h>
99 #endif /* SKEY */
100 
101 #include "pathnames.h"
102 
103 void	 badlogin __P((char *));
104 void	 checknologin __P((void));
105 void	 dolastlog __P((int));
106 void	 getloginname __P((void));
107 void	 motd __P((char *));
108 int	 rootterm __P((char *));
109 void	 sigint __P((int));
110 void	 sleepexit __P((int));
111 void	 refused __P((char *,char *,int));
112 char	*stypeof __P((char *));
113 void	 timedout __P((int));
114 void     login_fbtab __P((char *, uid_t, gid_t));
115 #ifdef KERBEROS
116 int	 klogin __P((struct passwd *, char *, char *, char *));
117 #endif
118 
119 extern void login __P((struct utmp *));
120 static void usage __P((void));
121 
122 #define	TTYGRPNAME	"tty"		/* name of group to own ttys */
123 #define	DEFAULT_BACKOFF	3
124 #define	DEFAULT_RETRIES	10
125 
126 /*
127  * This bounds the time given to login.  Not a define so it can
128  * be patched on machines where it's too small.
129  */
130 u_int	timeout = 300;
131 
132 #ifdef KERBEROS
133 int	notickets = 1;
134 int	noticketsdontcomplain = 1;
135 char	*instance;
136 char	*krbtkfile_env;
137 int	authok;
138 #endif
139 
140 struct	passwd *pwd;
141 int	failures;
142 char	*term, *envinit[1], *hostname, *username, *tty;
143 char    full_hostname[MAXHOSTNAMELEN];
144 
145 int
146 main(argc, argv)
147 	int argc;
148 	char *argv[];
149 {
150 	extern char **environ;
151 	struct group *gr;
152 	struct stat st;
153 	struct timeval tp;
154 	struct utmp utmp;
155 	int rootok, retries, backoff;
156 	int ask, ch, cnt, fflag, hflag, pflag, quietlog, rootlogin, rval;
157 	int changepass;
158 	time_t warntime;
159 	uid_t uid;
160 	char *domain, *p, *ep, *salt, *ttyn;
161 	char tbuf[MAXPATHLEN + 2], tname[sizeof(_PATH_TTY) + 10];
162 	char localhost[MAXHOSTNAMELEN];
163 	char *shell = NULL;
164 #ifdef LOGIN_CAP
165 	login_cap_t *lc = NULL;
166 #ifdef LOGIN_CAP_AUTH
167 	char *style, *authtype;
168 	char *auth_method = NULL;
169 	char *instance = NULL;
170 	int authok;
171 #endif /* LOGIN_CAP_AUTH */
172 #endif /* LOGIN_CAP */
173 #ifdef SKEY
174 	int permit_passwd = 0;
175 #endif /* SKEY */
176 
177 	(void)signal(SIGALRM, timedout);
178 	(void)alarm(timeout);
179 	(void)signal(SIGQUIT, SIG_IGN);
180 	(void)signal(SIGINT, SIG_IGN);
181 	(void)setpriority(PRIO_PROCESS, 0, 0);
182 
183 	openlog("login", LOG_ODELAY, LOG_AUTH);
184 
185 	/*
186 	 * -p is used by getty to tell login not to destroy the environment
187 	 * -f is used to skip a second login authentication
188 	 * -h is used by other servers to pass the name of the remote
189 	 *    host to login so that it may be placed in utmp and wtmp
190 	 */
191 	*full_hostname = '\0';
192 	domain = NULL;
193 	term = NULL;
194 	if (gethostname(localhost, sizeof(localhost)) < 0)
195 		syslog(LOG_ERR, "couldn't get local hostname: %m");
196 	else
197 		domain = strchr(localhost, '.');
198 
199 	fflag = hflag = pflag = 0;
200 	uid = getuid();
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 			strncpy(full_hostname, optarg, sizeof(full_hostname)-1);
211 			if (domain && (p = strchr(optarg, '.')) &&
212 			    strcasecmp(p, domain) == 0)
213 				*p = 0;
214 			if (strlen(optarg) > UT_HOSTSIZE) {
215 				struct hostent *hp = gethostbyname(optarg);
216 
217 				if (hp != NULL) {
218 					struct in_addr in;
219 
220 					memmove(&in, hp->h_addr, sizeof(in));
221 					optarg = strdup(inet_ntoa(in));
222 				} else
223 					optarg = "invalid hostname";
224 			}
225 			hostname = optarg;
226 			break;
227 		case 'p':
228 			pflag = 1;
229 			break;
230 		case '?':
231 		default:
232 			if (!uid)
233 				syslog(LOG_ERR, "invalid flag %c", ch);
234 			usage();
235 		}
236 	argc -= optind;
237 	argv += optind;
238 
239 	if (*argv) {
240 		username = *argv;
241 		ask = 0;
242 	} else
243 		ask = 1;
244 
245 	for (cnt = getdtablesize(); cnt > 2; cnt--)
246 		(void)close(cnt);
247 
248 	ttyn = ttyname(STDIN_FILENO);
249 	if (ttyn == NULL || *ttyn == '\0') {
250 		(void)snprintf(tname, sizeof(tname), "%s??", _PATH_TTY);
251 		ttyn = tname;
252 	}
253 	if ((tty = strrchr(ttyn, '/')) != NULL)
254 		++tty;
255 	else
256 		tty = ttyn;
257 
258 #ifdef LOGIN_CAP_AUTH
259 	authtype = hostname ? "rlogin" : "login";
260 #endif
261 #ifdef LOGIN_CAP
262 	/*
263 	 * Get "login-retries" & "login-backoff" from default class
264 	 */
265 	lc = login_getclass(NULL);
266 	retries = login_getcapnum(lc, "login-retries", DEFAULT_RETRIES, DEFAULT_RETRIES);
267 	backoff = login_getcapnum(lc, "login-backoff", DEFAULT_BACKOFF, DEFAULT_BACKOFF);
268 	login_close(lc);
269 	lc = NULL;
270 #else
271 	retries = DEFAULT_RETRIES;
272 	backoff = DEFAULT_BACKOFF;
273 #endif
274 
275 	for (cnt = 0;; ask = 1) {
276 		if (ask) {
277 			fflag = 0;
278 			getloginname();
279 		}
280 		rootlogin = 0;
281 		rootok = rootterm(tty); /* Default (auth may change) */
282 #ifdef LOGIN_CAP_AUTH
283 		authok = 0;
284 		if (auth_method = strchr(username, ':')) {
285 			*auth_method = '\0';
286 			auth_method++;
287 			if (*auth_method == '\0')
288 				auth_method = NULL;
289 		}
290 		/*
291 		 * We need to do this regardless of whether
292 		 * kerberos is available.
293 		 */
294 		if ((instance = strchr(username, '.')) != NULL) {
295 			if (strncmp(instance, ".root", 5) == 0)
296 				rootlogin = 1;
297 			*instance++ = '\0';
298 		} else
299 			instance = "";
300 #else /* !LOGIN_CAP_AUTH */
301 #ifdef KERBEROS
302 		if ((instance = strchr(username, '.')) != NULL) {
303 			if (strncmp(instance, ".root", 5) == 0)
304 				rootlogin = 1;
305 			*instance++ = '\0';
306 		} else
307 			instance = "";
308 #endif /* KERBEROS */
309 #endif /* LOGIN_CAP_AUTH */
310 
311 		if (strlen(username) > UT_NAMESIZE)
312 			username[UT_NAMESIZE] = '\0';
313 
314 		/*
315 		 * Note if trying multiple user names; log failures for
316 		 * previous user name, but don't bother logging one failure
317 		 * for nonexistent name (mistyped username).
318 		 */
319 		if (failures && strcmp(tbuf, username)) {
320 			if (failures > (pwd ? 0 : 1))
321 				badlogin(tbuf);
322 			failures = 0;
323 		}
324 		(void)strncpy(tbuf, username, sizeof tbuf-1);
325 		tbuf[sizeof tbuf-1] = '\0';
326 
327 		if ((pwd = getpwnam(username)) != NULL)
328 			salt = pwd->pw_passwd;
329 		else
330 			salt = "xx";
331 
332 #ifdef LOGIN_CAP
333 		/*
334 		 * Establish the class now, before we might goto
335 		 * within the next block. pwd can be NULL since it
336 		 * falls back to the "default" class if it is.
337 		 */
338 		lc = login_getpwclass(pwd);
339 #endif /* LOGIN_CAP */
340 
341 		/*
342 		 * if we have a valid account name, and it doesn't have a
343 		 * password, or the -f option was specified and the caller
344 		 * is root or the caller isn't changing their uid, don't
345 		 * authenticate.
346 		 */
347 		rval = 1;
348 		if (pwd != NULL) {
349 			if (pwd->pw_uid == 0)
350 				rootlogin = 1;
351 
352 			if (fflag && (uid == (uid_t)0 ||
353 				      uid == (uid_t)pwd->pw_uid)) {
354 				/* already authenticated */
355 				break;
356 			} else if (pwd->pw_passwd[0] == '\0') {
357 				if (!rootlogin || rootok) {
358 					/* pretend password okay */
359 					rval = 0;
360 					goto ttycheck;
361 				}
362 			}
363 		}
364 
365 		fflag = 0;
366 
367 		(void)setpriority(PRIO_PROCESS, 0, -4);
368 
369 #ifdef LOGIN_CAP_AUTH
370 		/*
371 		 * This hands off authorization to an authorization program,
372 		 * depending on the styles available for the "auth-login",
373 		 * auth-rlogin (or default) authorization styles.
374 		 * We do this regardless of whether an account exists so that
375 		 * the remote user cannot tell a "real" from an invented
376 		 * account name. If we don't have an account we just fall
377 		 * back to the first method for the "default" class.
378 		 */
379 		if (!(style = login_getstyle(lc, auth_method, authtype))) {
380 
381 			/*
382 			 * No available authorization method
383 			 */
384 			rval = 1;
385 			(void)printf("No auth method available for %s.\n",
386 				     authtype);
387 		} else {
388 
389 			/*
390 			 * Put back the kerberos instance, if any was given.
391 			 * Don't worry about the non-kerberos case here, since
392 			 * if kerberos is not available or not selected and an
393 			 * instance is given at the login prompt, su or rlogin -l,
394 			 * then anything else should fail as well.
395 			 */
396 			if (*instance)
397 				*(instance - 1) = '.';
398 
399 			rval = authenticate(username,
400 					    lc ? lc->lc_class : "default",
401 					    style, authtype);
402 			/* Junk it again */
403 			if (*instance)
404 				*(instance - 1) = '\0';
405 		}
406 
407 		if (!rval) {
408 			char * approvp;
409 
410 			/*
411 			 * If authentication succeeds, run any approval
412 			 * program, if applicable for this class.
413 			 */
414 			approvep = login_getcapstr(lc, "approve", NULL, NULL);
415 			rval = 1; /* Assume bad login again */
416 
417 			if (approvep==NULL ||
418 			    auth_script(approvep, approvep, username,
419 					lc->lc_class, 0) == 0) {
420 				int     r;
421 
422 				r = auth_scan(AUTH_OKAY);
423 				/*
424 				 * See what the authorize program says
425 				 */
426 				if (r != AUTH_NONE) {
427 					rval = 0;
428 
429 					if (!rootok && (r & AUTH_ROOTOKAY))
430 						rootok = 1; /* root approved */
431 					else
432 						rootlogin = 0;
433 
434 					if (!authok && (r & AUTH_SECURE))
435 						authok = 1; /* secure */
436 				}
437 			}
438 		}
439 #else /* !LOGIN_CAP_AUTH */
440 #ifdef SKEY
441 		permit_passwd = skeyaccess(username, tty,
442 					   hostname ? full_hostname : NULL,
443 					   NULL);
444 		p = skey_getpass("Password:", pwd, permit_passwd);
445 		ep = skey_crypt(p, salt, pwd, permit_passwd);
446 #else /* !SKEY */
447 		p = getpass("Password:");
448 		ep = crypt(p, salt);
449 #endif/* SKEY */
450 
451 		if (pwd) {
452 #ifdef KERBEROS
453 #ifdef SKEY
454 			/*
455 			 * Do not allow user to type in kerberos password
456 			 * over the net (actually, this is ok for encrypted
457 			 * links, but we have no way of determining if the
458 			 * link is encrypted.
459 			 */
460 			if (!permit_passwd) {
461 				rval = 1;		/* failed */
462 			} else
463 #endif /* SKEY */
464 			rval = klogin(pwd, instance, localhost, p);
465 			if (rval != 0 && rootlogin && pwd->pw_uid != 0)
466 				rootlogin = 0;
467 			if (rval == 0)
468 				authok = 1; /* kerberos authenticated ok */
469 			else if (rval == 1) /* fallback to unix passwd */
470 				rval = strcmp(ep, pwd->pw_passwd);
471 #else /* !KERBEROS */
472 			rval = strcmp(ep, pwd->pw_passwd);
473 #endif /* KERBEROS */
474 		}
475 
476 		/* clear entered password */
477 		memset(p, 0, strlen(p));
478 #endif /* LOGIN_CAP_AUTH */
479 
480 		(void)setpriority(PRIO_PROCESS, 0, 0);
481 
482 #ifdef LOGIN_CAP_AUTH
483 		if (rval)
484 			auth_rmfiles();
485 #endif
486 	ttycheck:
487 		/*
488 		 * If trying to log in as root without Kerberos,
489 		 * but with insecure terminal, refuse the login attempt.
490 		 */
491 		if (pwd && !rval) {
492 #if defined(KERBEROS) || defined(LOGIN_CAP_AUTH)
493 			if (authok == 0 && rootlogin && !rootok)
494 #else
495 			if (rootlogin && !rootok)
496 #endif
497 				refused(NULL, "NOROOT", 0);
498 			else	/* valid password & authenticated */
499 				break;
500 		}
501 
502 		(void)printf("Login incorrect\n");
503 		failures++;
504 
505 		/*
506 		 * we allow up to 'retry' (10) tries,
507 		 * but after 'backoff' (3) we start backing off
508 		 */
509 		if (++cnt > backoff) {
510 			if (cnt >= retries) {
511 				badlogin(username);
512 				sleepexit(1);
513 			}
514 			sleep((u_int)((cnt - 3) * 5));
515 		}
516 	}
517 
518 	/* committed to login -- turn off timeout */
519 	(void)alarm((u_int)0);
520 
521 	endpwent();
522 
523 	/* if user not super-user, check for disabled logins */
524 #ifdef LOGIN_CAP
525 	if (!rootlogin)
526 		auth_checknologin(lc);
527 #else
528 	if (!rootlogin)
529 		checknologin();
530 #endif
531 
532 #ifdef LOGIN_CAP
533 	quietlog = login_getcapbool(lc, "hushlogin", 0);
534 #else
535 	quietlog = 0;
536 #endif
537 	if (!*pwd->pw_dir || chdir(pwd->pw_dir) < 0) {
538 #ifdef LOGIN_CAP
539 		if (login_getcapbool(lc, "requirehome", 0))
540 			refused("Home directory not available", "HOMEDIR", 1);
541 #endif
542 		if (chdir("/") < 0)
543 			refused("Cannot find root directory", "ROOTDIR", 1);
544 		pwd->pw_dir = "/";
545 		if (!quietlog || *pwd->pw_dir)
546 			printf("No home directory.\nLogging in with home = \"/\".\n");
547 	}
548 	if (!quietlog)
549 		quietlog = access(_PATH_HUSHLOGIN, F_OK) == 0;
550 
551 	if (pwd->pw_change || pwd->pw_expire)
552 		(void)gettimeofday(&tp, (struct timezone *)NULL);
553 
554 #define DEFAULT_WARN  (2L * 7L & 86400L)  /* Two weeks */
555 
556 #ifdef LOGIN_CAP
557 	warntime = login_getcaptime(lc, "warnpassword",
558 				    DEFAULT_WARN, DEFAULT_WARN);
559 #else
560 	warntime = DEFAULT_WARN;
561 #endif
562 
563 	changepass=0;
564 	if (pwd->pw_change) {
565 		if (tp.tv_sec >= pwd->pw_change) {
566 			(void)printf("Sorry -- your password has expired.\n");
567 			changepass=1;
568 			syslog(LOG_INFO,
569 			       "%s Password expired - forcing change",
570 			       pwd->pw_name);
571 		} else if (pwd->pw_change - tp.tv_sec < warntime && !quietlog)
572 		    (void)printf("Warning: your password expires on %s",
573 				 ctime(&pwd->pw_change));
574 	}
575 
576 #ifdef LOGIN_CAP
577 	warntime = login_getcaptime(lc, "warnexpire",
578 				    DEFAULT_WARN, DEFAULT_WARN);
579 #else
580 	warntime = DEFAULT_WARN;
581 #endif
582 
583 	if (pwd->pw_expire) {
584 		if (tp.tv_sec >= pwd->pw_expire) {
585 			refused("Sorry -- your account has expired",
586 				"EXPIRED", 1);
587 		} else if (pwd->pw_expire - tp.tv_sec < warntime && !quietlog)
588 		    (void)printf("Warning: your account expires on %s",
589 				 ctime(&pwd->pw_expire));
590 	}
591 
592 #ifdef LOGIN_CAP
593 	if (lc != NULL) {
594 		if (hostname) {
595 			struct hostent *hp = gethostbyname(full_hostname);
596 
597 			if (hp == NULL)
598 				optarg = NULL;
599 			else {
600 				struct in_addr in;
601 				memmove(&in, hp->h_addr, sizeof(in));
602 				optarg = strdup(inet_ntoa(in));
603 			}
604 			if (!auth_hostok(lc, full_hostname, optarg))
605 				refused("Permission denied", "HOST", 1);
606 		}
607 
608 		if (!auth_ttyok(lc, tty))
609 			refused("Permission denied", "TTY", 1);
610 
611 		if (!auth_timeok(lc, time(NULL)))
612 			refused("Logins not available right now", "TIME", 1);
613 	}
614         shell=login_getcapstr(lc, "shell", pwd->pw_shell, pwd->pw_shell);
615 #else /* !LOGIN_CAP */
616        shell=pwd->pw_shell;
617 #endif /* LOGIN_CAP */
618 	if (*pwd->pw_shell == '\0')
619 		pwd->pw_shell = _PATH_BSHELL;
620 	if (*shell == '\0')   /* Not overridden */
621 		shell = pwd->pw_shell;
622 	if ((shell = strdup(shell)) == NULL) {
623 		syslog(LOG_NOTICE, "memory allocation error");
624 		sleepexit(1);
625 	}
626 
627 #ifdef LOGIN_ACCESS
628 	if (login_access(pwd->pw_name, hostname ? full_hostname : tty) == 0)
629 		refused("Permission denied", "ACCESS", 1);
630 #endif /* LOGIN_ACCESS */
631 
632 	/* Nothing else left to fail -- really log in. */
633 	memset((void *)&utmp, 0, sizeof(utmp));
634 	(void)time(&utmp.ut_time);
635 	(void)strncpy(utmp.ut_name, username, sizeof(utmp.ut_name));
636 	if (hostname)
637 		(void)strncpy(utmp.ut_host, hostname, sizeof(utmp.ut_host));
638 	(void)strncpy(utmp.ut_line, tty, sizeof(utmp.ut_line));
639 	login(&utmp);
640 
641 	dolastlog(quietlog);
642 
643 	/*
644 	 * Set device protections, depending on what terminal the
645 	 * user is logged in. This feature is used on Suns to give
646 	 * console users better privacy.
647 	 */
648 	login_fbtab(tty, pwd->pw_uid, pwd->pw_gid);
649 
650 	(void)chown(ttyn, pwd->pw_uid,
651 		    (gr = getgrnam(TTYGRPNAME)) ? gr->gr_gid : pwd->pw_gid);
652 
653 	/*
654 	 * Preserve TERM if it happens to be already set.
655 	 */
656 	if ((term = getenv("TERM")) != NULL)
657 		term = strdup(term);
658 
659 	/*
660 	 * Exclude cons/vt/ptys only, assume dialup otherwise
661 	 * TODO: Make dialup tty determination a library call
662 	 * for consistency (finger etc.)
663 	 */
664 	if (hostname==NULL && isdialuptty(tty))
665 		syslog(LOG_INFO, "DIALUP %s, %s", tty, pwd->pw_name);
666 
667 #ifdef KERBEROS
668 	if (!quietlog && notickets == 1 && !noticketsdontcomplain)
669 		(void)printf("Warning: no Kerberos tickets issued.\n");
670 #endif
671 
672 #ifdef LOGALL
673 	/*
674 	 * Syslog each successful login, so we don't have to watch hundreds
675 	 * of wtmp or lastlogin files.
676 	 */
677 	if (hostname)
678 		syslog(LOG_INFO, "login from %s on %s as %s",
679 		       full_hostname, tty, pwd->pw_name);
680 	else
681 		syslog(LOG_INFO, "login on %s as %s",
682 		       tty, pwd->pw_name);
683 #endif
684 
685 	/*
686 	 * If fflag is on, assume caller/authenticator has logged root login.
687 	 */
688 	if (rootlogin && fflag == 0)
689 	{
690 		if (hostname)
691 			syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s FROM %s",
692 			       username, tty, full_hostname);
693 		else
694 			syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s",
695 			       username, tty);
696 	}
697 
698 	/*
699 	 * Destroy environment unless user has requested its preservation.
700 	 * We need to do this before setusercontext() because that may
701 	 * set or reset some environment variables.
702 	 */
703 	if (!pflag)
704 		environ = envinit;
705 
706 	/*
707 	 * We don't need to be root anymore, so
708 	 * set the user and session context
709 	 */
710 #ifdef LOGIN_CAP
711 	if (setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETALL) != 0) {
712                 syslog(LOG_ERR, "setusercontext() failed - exiting");
713 		exit(1);
714 	}
715 #else
716      	if (setlogin(pwd->pw_name) < 0)
717                 syslog(LOG_ERR, "setlogin() failure: %m");
718 
719 	(void)setgid(pwd->pw_gid);
720 	initgroups(username, pwd->pw_gid);
721 	(void)setuid(rootlogin ? 0 : pwd->pw_uid);
722 #endif
723 
724 	(void)setenv("SHELL", pwd->pw_shell, 1);
725 	(void)setenv("HOME", pwd->pw_dir, 1);
726 	if (term != NULL && *term != '\0')
727 		(void)setenv("TERM", term, 1);	/* Preset overrides */
728 	else {
729 		(void)setenv("TERM", stypeof(tty), 0);	/* Fallback doesn't */
730 	}
731 	(void)setenv("LOGNAME", pwd->pw_name, 1);
732 	(void)setenv("USER", pwd->pw_name, 1);
733 	(void)setenv("PATH", rootlogin ? _PATH_STDPATH : _PATH_DEFPATH, 0);
734 #ifdef KERBEROS
735 	if (krbtkfile_env)
736 		(void)setenv("KRBTKFILE", krbtkfile_env, 1);
737 #endif
738 #if LOGIN_CAP_AUTH
739 	auth_env();
740 #endif
741 
742 #ifdef LOGIN_CAP
743 	if (!quietlog) {
744 		char	*cw;
745 
746 		cw = login_getcapstr(lc, "copyright", NULL, NULL);
747 		if (cw != NULL && access(cw, F_OK) == 0)
748 			motd(cw);
749 		else
750 		    (void)printf("%s\n\t%s %s\n",
751 	"Copyright (c) 1980, 1983, 1986, 1988, 1990, 1991, 1993, 1994",
752 	"The Regents of the University of California. ",
753 	"All rights reserved.");
754 
755 		(void)printf("\n");
756 
757 		cw = login_getcapstr(lc, "welcome", NULL, NULL);
758 		if (cw == NULL || access(cw, F_OK) != 0)
759 			cw = _PATH_MOTDFILE;
760 		motd(cw);
761 
762 		cw = getenv("MAIL");	/* $MAIL may have been set by class */
763 		if (cw != NULL) {
764 			strncpy(tbuf, cw, sizeof(tbuf));
765 			tbuf[sizeof(tbuf)-1] = '\0';
766 		} else
767 			snprintf(tbuf, sizeof(tbuf), "%s/%s",
768 				 _PATH_MAILDIR, pwd->pw_name);
769 #else
770 	if (!quietlog) {
771 		    (void)printf("%s\n\t%s %s\n",
772 	"Copyright (c) 1980, 1983, 1986, 1988, 1990, 1991, 1993, 1994",
773 	"The Regents of the University of California. ",
774 	"All rights reserved.");
775 		motd(_PATH_MOTDFILE);
776 		snprintf(tbuf, sizeof(tbuf), "%s/%s",
777 			 _PATH_MAILDIR, pwd->pw_name);
778 #endif
779 		if (stat(tbuf, &st) == 0 && st.st_size != 0)
780 			(void)printf("You have %smail.\n",
781 				     (st.st_mtime > st.st_atime) ? "new " : "");
782 	}
783 
784 #ifdef LOGIN_CAP
785 	login_close(lc);
786 #endif
787 
788 	(void)signal(SIGALRM, SIG_DFL);
789 	(void)signal(SIGQUIT, SIG_DFL);
790 	(void)signal(SIGINT, SIG_DFL);
791 	(void)signal(SIGTSTP, SIG_IGN);
792 
793 	if (changepass) {
794 		if (system(_PATH_CHPASS) != 0)
795 			sleepexit(1);
796 	}
797 
798 	/*
799 	 * Login shells have a leading '-' in front of argv[0]
800 	 */
801 	tbuf[0] = '-';
802 	(void)strcpy(tbuf + 1, (p = strrchr(pwd->pw_shell, '/')) ? p + 1 : pwd->pw_shell);
803 
804 	execlp(shell, tbuf, 0);
805 	err(1, "%s", shell);
806 }
807 
808 static void
809 usage()
810 {
811 	(void)fprintf(stderr, "usage: login [-fp] [-h hostname] [username]\n");
812 	exit(1);
813 }
814 
815 /*
816  * Allow for authentication style and/or kerberos instance
817  * */
818 
819 #define	NBUFSIZ		UT_NAMESIZE + 64
820 
821 void
822 getloginname()
823 {
824 	int ch;
825 	char *p;
826 	static char nbuf[NBUFSIZ];
827 
828 	for (;;) {
829 		(void)printf("login: ");
830 		for (p = nbuf; (ch = getchar()) != '\n'; ) {
831 			if (ch == EOF) {
832 				badlogin(username);
833 				exit(0);
834 			}
835 			if (p < nbuf + (NBUFSIZ - 1))
836 				*p++ = ch;
837 		}
838 		if (p > nbuf)
839 			if (nbuf[0] == '-')
840 				(void)fprintf(stderr,
841 				    "login names may not start with '-'.\n");
842 			else {
843 				*p = '\0';
844 				username = nbuf;
845 				break;
846 			}
847 	}
848 }
849 
850 int
851 rootterm(ttyn)
852 	char *ttyn;
853 {
854 	struct ttyent *t;
855 
856 	return ((t = getttynam(ttyn)) && t->ty_status & TTY_SECURE);
857 }
858 
859 volatile int motdinterrupt;
860 
861 /* ARGSUSED */
862 void
863 sigint(signo)
864 	int signo;
865 {
866 	motdinterrupt = 1;
867 }
868 
869 void
870 motd(motdfile)
871 	char *motdfile;
872 {
873 	int fd, nchars;
874 	sig_t oldint;
875 	char tbuf[256];
876 
877 	if ((fd = open(motdfile, O_RDONLY, 0)) < 0)
878 		return;
879 	motdinterrupt = 0;
880 	oldint = signal(SIGINT, sigint);
881 	while ((nchars = read(fd, tbuf, sizeof(tbuf))) > 0 && !motdinterrupt)
882 		(void)write(fileno(stdout), tbuf, nchars);
883 	(void)signal(SIGINT, oldint);
884 	(void)close(fd);
885 }
886 
887 /* ARGSUSED */
888 void
889 timedout(signo)
890 	int signo;
891 {
892 	(void)fprintf(stderr, "Login timed out after %d seconds\n", timeout);
893 	exit(0);
894 }
895 
896 #ifndef LOGIN_CAP
897 void
898 checknologin()
899 {
900 	int fd, nchars;
901 	char tbuf[8192];
902 
903 	if ((fd = open(_PATH_NOLOGIN, O_RDONLY, 0)) >= 0) {
904 		while ((nchars = read(fd, tbuf, sizeof(tbuf))) > 0)
905 			(void)write(fileno(stdout), tbuf, nchars);
906 		sleepexit(0);
907 	}
908 }
909 #endif
910 
911 void
912 dolastlog(quiet)
913 	int quiet;
914 {
915 	struct lastlog ll;
916 	int fd;
917 
918 	if ((fd = open(_PATH_LASTLOG, O_RDWR, 0)) >= 0) {
919 		(void)lseek(fd, (off_t)pwd->pw_uid * sizeof(ll), L_SET);
920 		if (!quiet) {
921 			if (read(fd, (char *)&ll, sizeof(ll)) == sizeof(ll) &&
922 			    ll.ll_time != 0) {
923 				(void)printf("Last login: %.*s ",
924 				    24-5, (char *)ctime(&ll.ll_time));
925 				if (*ll.ll_host != '\0')
926 					(void)printf("from %.*s\n",
927 					    (int)sizeof(ll.ll_host),
928 					    ll.ll_host);
929 				else
930 					(void)printf("on %.*s\n",
931 					    (int)sizeof(ll.ll_line),
932 					    ll.ll_line);
933 			}
934 			(void)lseek(fd, (off_t)pwd->pw_uid * sizeof(ll), L_SET);
935 		}
936 		memset((void *)&ll, 0, sizeof(ll));
937 		(void)time(&ll.ll_time);
938 		(void)strncpy(ll.ll_line, tty, sizeof(ll.ll_line));
939 		if (hostname)
940 			(void)strncpy(ll.ll_host, hostname, sizeof(ll.ll_host));
941 		(void)write(fd, (char *)&ll, sizeof(ll));
942 		(void)close(fd);
943 	}
944 }
945 
946 void
947 badlogin(name)
948 	char *name;
949 {
950 
951 	if (failures == 0)
952 		return;
953 	if (hostname) {
954 		syslog(LOG_NOTICE, "%d LOGIN FAILURE%s FROM %s",
955 		    failures, failures > 1 ? "S" : "", full_hostname);
956 		syslog(LOG_AUTHPRIV|LOG_NOTICE,
957 		    "%d LOGIN FAILURE%s FROM %s, %s",
958 		    failures, failures > 1 ? "S" : "", full_hostname, name);
959 	} else {
960 		syslog(LOG_NOTICE, "%d LOGIN FAILURE%s ON %s",
961 		    failures, failures > 1 ? "S" : "", tty);
962 		syslog(LOG_AUTHPRIV|LOG_NOTICE,
963 		    "%d LOGIN FAILURE%s ON %s, %s",
964 		    failures, failures > 1 ? "S" : "", tty, name);
965 	}
966 }
967 
968 #undef	UNKNOWN
969 #define	UNKNOWN	"su"
970 
971 char *
972 stypeof(ttyid)
973 	char *ttyid;
974 {
975 
976 	struct ttyent *t;
977 
978 	return (ttyid && (t = getttynam(ttyid)) ? t->ty_type : UNKNOWN);
979 }
980 
981 void
982 refused(msg, rtype, lout)
983 	char *msg;
984 	char *rtype;
985 	int lout;
986 {
987 
988 	if (msg != NULL)
989 	    printf("%s.\n", msg);
990 	if (hostname)
991 		syslog(LOG_NOTICE, "LOGIN %s REFUSED (%s) FROM %s ON TTY %s",
992 		       pwd->pw_name, rtype, full_hostname, tty);
993 	else
994 		syslog(LOG_NOTICE, "LOGIN %s REFUSED (%s) ON TTY %s",
995 		       pwd->pw_name, rtype, tty);
996 	if (lout)
997 		sleepexit(1);
998 }
999 
1000 void
1001 sleepexit(eval)
1002 	int eval;
1003 {
1004 
1005 	(void)sleep(5);
1006 	exit(eval);
1007 }
1008