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