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