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