xref: /freebsd/usr.bin/login/login.c (revision 5f757f3f)
1 /*-
2  * SPDX-License-Identifier: BSD-4-Clause
3  *
4  * Copyright (c) 1980, 1987, 1988, 1991, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  * Copyright (c) 2002 Networks Associates Technologies, Inc.
7  * All rights reserved.
8  *
9  * Portions of this software were developed for the FreeBSD Project by
10  * ThinkSec AS and NAI Labs, the Security Research Division of Network
11  * Associates, Inc.  under DARPA/SPAWAR contract N66001-01-C-8035
12  * ("CBOSS"), as part of the DARPA CHATS research program.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. All advertising materials mentioning features or use of this software
23  *    must display the following acknowledgement:
24  *	This product includes software developed by the University of
25  *	California, Berkeley and its contributors.
26  * 4. Neither the name of the University nor the names of its contributors
27  *    may be used to endorse or promote products derived from this software
28  *    without specific prior written permission.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40  * SUCH DAMAGE.
41  */
42 
43 #include <sys/cdefs.h>
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/param.h>
51 #include <sys/file.h>
52 #include <sys/stat.h>
53 #include <sys/time.h>
54 #include <sys/resource.h>
55 #include <sys/wait.h>
56 
57 #include <err.h>
58 #include <errno.h>
59 #include <grp.h>
60 #include <login_cap.h>
61 #include <pwd.h>
62 #include <setjmp.h>
63 #include <signal.h>
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <string.h>
67 #include <syslog.h>
68 #include <ttyent.h>
69 #include <unistd.h>
70 
71 #include <security/pam_appl.h>
72 #include <security/openpam.h>
73 
74 #include "login.h"
75 #include "pathnames.h"
76 
77 static int		 auth_pam(void);
78 static void		 bail(int, int);
79 static void		 bail_internal(int, int, int);
80 static int		 export(const char *);
81 static void		 export_pam_environment(void);
82 static int		 motd(const char *);
83 static void		 badlogin(char *);
84 static char		*getloginname(void);
85 static void		 pam_syslog(const char *);
86 static void		 pam_cleanup(void);
87 static void		 refused(const char *, const char *, int);
88 static const char	*stypeof(char *);
89 static void		 sigint(int);
90 static void		 timedout(int);
91 static void		 bail_sig(int);
92 static void		 usage(void);
93 
94 #define	TTYGRPNAME		"tty"			/* group to own ttys */
95 #define	DEFAULT_BACKOFF		3
96 #define	DEFAULT_RETRIES		10
97 #define	DEFAULT_PROMPT		"login: "
98 #define	DEFAULT_PASSWD_PROMPT	"Password:"
99 #define	TERM_UNKNOWN		"su"
100 #define	DEFAULT_WARN		(2L * 7L * 86400L)	/* Two weeks */
101 #define	NO_SLEEP_EXIT		0
102 #define	SLEEP_EXIT		5
103 
104 /*
105  * This bounds the time given to login.  Not a define so it can
106  * be patched on machines where it's too small.
107  */
108 static u_int		timeout = 300;
109 
110 /* Buffer for signal handling of timeout */
111 static jmp_buf		 timeout_buf;
112 
113 char			 pwbuf[1024];
114 struct passwd		 pwres;
115 struct passwd		*pwd;
116 static int		 failures;
117 
118 static char		*envinit[1];	/* empty environment list */
119 
120 /*
121  * Command line flags and arguments
122  */
123 static int		 fflag;		/* -f: do not perform authentication */
124 static int		 hflag;		/* -h: login from remote host */
125 static char		*hostname;	/* hostname from command line */
126 static int		 pflag;		/* -p: preserve environment */
127 
128 /*
129  * User name
130  */
131 static char		*username;	/* user name */
132 static char		*olduser;	/* previous user name */
133 
134 /*
135  * Prompts
136  */
137 static char		 default_prompt[] = DEFAULT_PROMPT;
138 static const char	*prompt;
139 static char		 default_passwd_prompt[] = DEFAULT_PASSWD_PROMPT;
140 static const char	*passwd_prompt;
141 
142 static char		*tty;
143 
144 /*
145  * PAM data
146  */
147 static pam_handle_t	*pamh = NULL;
148 static struct pam_conv	 pamc = { openpam_ttyconv, NULL };
149 static int		 pam_err;
150 static int		 pam_silent = PAM_SILENT;
151 static int		 pam_cred_established;
152 static int		 pam_session_established;
153 
154 int
155 main(int argc, char *argv[])
156 {
157 	struct group *gr;
158 	struct stat st;
159 	int retries, backoff;
160 	int ask, ch, cnt, quietlog, rootlogin, rval;
161 	uid_t uid, euid;
162 	gid_t egid;
163 	char *term;
164 	char *p, *ttyn;
165 	char tname[sizeof(_PATH_TTY) + 10];
166 	char *arg0;
167 	const char *tp;
168 	const char *shell = NULL;
169 	login_cap_t *lc = NULL;
170 	login_cap_t *lc_user = NULL;
171 	pid_t pid;
172 	sigset_t mask, omask;
173 	struct sigaction sa;
174 #ifdef USE_BSM_AUDIT
175 	char auditsuccess = 1;
176 #endif
177 
178 	sa.sa_flags = SA_RESTART;
179 	(void)sigfillset(&sa.sa_mask);
180 	sa.sa_handler = SIG_IGN;
181 	(void)sigaction(SIGQUIT, &sa, NULL);
182 	(void)sigaction(SIGINT, &sa, NULL);
183 	(void)sigaction(SIGHUP, &sa, NULL);
184 	if (setjmp(timeout_buf)) {
185 		if (failures)
186 			badlogin(username);
187 		(void)fprintf(stderr, "Login timed out after %d seconds\n",
188 		    timeout);
189 		bail(NO_SLEEP_EXIT, 0);
190 	}
191 	sa.sa_handler = timedout;
192 	(void)sigaction(SIGALRM, &sa, NULL);
193 	(void)alarm(timeout);
194 	(void)setpriority(PRIO_PROCESS, 0, 0);
195 
196 	openlog("login", LOG_CONS, LOG_AUTH);
197 
198 	uid = getuid();
199 	euid = geteuid();
200 	egid = getegid();
201 
202 	while ((ch = getopt(argc, argv, "fh:p")) != -1)
203 		switch (ch) {
204 		case 'f':
205 			fflag = 1;
206 			break;
207 		case 'h':
208 			if (uid != 0)
209 				errx(1, "-h option: %s", strerror(EPERM));
210 			if (strlen(optarg) >= MAXHOSTNAMELEN)
211 				errx(1, "-h option: %s: exceeds maximum "
212 				    "hostname size", optarg);
213 			hflag = 1;
214 			hostname = optarg;
215 			break;
216 		case 'p':
217 			pflag = 1;
218 			break;
219 		case '?':
220 		default:
221 			if (uid == 0)
222 				syslog(LOG_ERR, "invalid flag %c", ch);
223 			usage();
224 		}
225 	argc -= optind;
226 	argv += optind;
227 
228 	if (argc > 0) {
229 		username = strdup(*argv);
230 		if (username == NULL)
231 			err(1, "strdup()");
232 		ask = 0;
233 	} else {
234 		ask = 1;
235 	}
236 
237 	setproctitle("-%s", getprogname());
238 
239 	closefrom(3);
240 
241 	/*
242 	 * Get current TTY
243 	 */
244 	ttyn = ttyname(STDIN_FILENO);
245 	if (ttyn == NULL || *ttyn == '\0') {
246 		(void)snprintf(tname, sizeof(tname), "%s??", _PATH_TTY);
247 		ttyn = tname;
248 	}
249 	if (strncmp(ttyn, _PATH_DEV, sizeof _PATH_DEV - 1) == 0)
250 		tty = ttyn + sizeof _PATH_DEV - 1;
251 	else
252 		tty = ttyn;
253 
254 	/*
255 	 * Get "login-retries" & "login-backoff" from default class
256 	 */
257 	lc = login_getclass(NULL);
258 	prompt = login_getcapstr(lc, "login_prompt",
259 	    default_prompt, default_prompt);
260 	passwd_prompt = login_getcapstr(lc, "passwd_prompt",
261 	    default_passwd_prompt, default_passwd_prompt);
262 	retries = login_getcapnum(lc, "login-retries",
263 	    DEFAULT_RETRIES, DEFAULT_RETRIES);
264 	backoff = login_getcapnum(lc, "login-backoff",
265 	    DEFAULT_BACKOFF, DEFAULT_BACKOFF);
266 	login_close(lc);
267 	lc = NULL;
268 
269 	/*
270 	 * Try to authenticate the user until we succeed or time out.
271 	 */
272 	for (cnt = 0;; ask = 1) {
273 		if (ask) {
274 			fflag = 0;
275 			if (olduser != NULL)
276 				free(olduser);
277 			olduser = username;
278 			username = getloginname();
279 		}
280 		rootlogin = 0;
281 
282 		/*
283 		 * Note if trying multiple user names; log failures for
284 		 * previous user name, but don't bother logging one failure
285 		 * for nonexistent name (mistyped username).
286 		 */
287 		if (failures && strcmp(olduser, username) != 0) {
288 			if (failures > (pwd ? 0 : 1))
289 				badlogin(olduser);
290 		}
291 
292 		/*
293 		 * Load the PAM policy and set some variables
294 		 */
295 		pam_err = pam_start("login", username, &pamc, &pamh);
296 		if (pam_err != PAM_SUCCESS) {
297 			pam_syslog("pam_start()");
298 #ifdef USE_BSM_AUDIT
299 			au_login_fail("PAM Error", 1);
300 #endif
301 			bail(NO_SLEEP_EXIT, 1);
302 		}
303 		pam_err = pam_set_item(pamh, PAM_TTY, tty);
304 		if (pam_err != PAM_SUCCESS) {
305 			pam_syslog("pam_set_item(PAM_TTY)");
306 #ifdef USE_BSM_AUDIT
307 			au_login_fail("PAM Error", 1);
308 #endif
309 			bail(NO_SLEEP_EXIT, 1);
310 		}
311 		pam_err = pam_set_item(pamh, PAM_RHOST, hostname);
312 		if (pam_err != PAM_SUCCESS) {
313 			pam_syslog("pam_set_item(PAM_RHOST)");
314 #ifdef USE_BSM_AUDIT
315 			au_login_fail("PAM Error", 1);
316 #endif
317 			bail(NO_SLEEP_EXIT, 1);
318 		}
319 
320 		(void)getpwnam_r(username, &pwres, pwbuf, sizeof(pwbuf), &pwd);
321 		if (pwd != NULL && pwd->pw_uid == 0)
322 			rootlogin = 1;
323 
324 		/*
325 		 * If the -f option was specified and the caller is
326 		 * root or the caller isn't changing their uid, don't
327 		 * authenticate.
328 		 */
329 		if (pwd != NULL && fflag &&
330 		    (uid == (uid_t)0 || uid == (uid_t)pwd->pw_uid)) {
331 			/* already authenticated */
332 			rval = 0;
333 #ifdef USE_BSM_AUDIT
334 			auditsuccess = 0; /* opened a terminal window only */
335 #endif
336 		} else {
337 			fflag = 0;
338 			(void)setpriority(PRIO_PROCESS, 0, -4);
339 			rval = auth_pam();
340 			(void)setpriority(PRIO_PROCESS, 0, 0);
341 		}
342 
343 		if (pwd != NULL && rval == 0)
344 			break;
345 
346 		pam_cleanup();
347 
348 		/*
349 		 * We are not exiting here, but this corresponds to a failed
350 		 * login event, so set exitstatus to 1.
351 		 */
352 #ifdef USE_BSM_AUDIT
353 		au_login_fail("Login incorrect", 1);
354 #endif
355 
356 		(void)printf("Login incorrect\n");
357 		failures++;
358 
359 		pwd = NULL;
360 
361 		/*
362 		 * Allow up to 'retry' (10) attempts, but start
363 		 * backing off after 'backoff' (3) attempts.
364 		 */
365 		if (++cnt > backoff) {
366 			if (cnt >= retries) {
367 				badlogin(username);
368 				bail(SLEEP_EXIT, 1);
369 			}
370 			sleep((u_int)((cnt - backoff) * 5));
371 		}
372 	}
373 
374 	/* committed to login -- turn off timeout */
375 	(void)alarm((u_int)0);
376 
377 	(void)sigemptyset(&mask);
378 	(void)sigaddset(&mask, SIGHUP);
379 	(void)sigaddset(&mask, SIGTERM);
380 	(void)sigprocmask(SIG_BLOCK, &mask, &omask);
381 	sa.sa_handler = bail_sig;
382 	(void)sigaction(SIGHUP, &sa, NULL);
383 	(void)sigaction(SIGTERM, &sa, NULL);
384 
385 	endpwent();
386 
387 #ifdef USE_BSM_AUDIT
388 	/* Audit successful login. */
389 	if (auditsuccess)
390 		au_login_success();
391 #endif
392 
393 	/*
394 	 * This needs to happen before login_getpwclass to support
395 	 * home directories on GSS-API authenticated NFS where the
396 	 * kerberos credentials need to be saved so that the kernel
397 	 * can authenticate to the NFS server.
398 	 */
399 	pam_err = pam_setcred(pamh, pam_silent|PAM_ESTABLISH_CRED);
400 	if (pam_err != PAM_SUCCESS) {
401 		pam_syslog("pam_setcred()");
402 		bail(NO_SLEEP_EXIT, 1);
403 	}
404 	pam_cred_established = 1;
405 
406 	/*
407 	 * Establish the login class.
408 	 */
409 	lc = login_getpwclass(pwd);
410 	lc_user = login_getuserclass(pwd);
411 
412 	if (!(quietlog = login_getcapbool(lc_user, "hushlogin", 0)))
413 		quietlog = login_getcapbool(lc, "hushlogin", 0);
414 
415 	/*
416 	 * Switching needed for NFS with root access disabled.
417 	 *
418 	 * XXX: This change fails to modify the additional groups for the
419 	 * process, and as such, may restrict rights normally granted
420 	 * through those groups.
421 	 */
422 	(void)setegid(pwd->pw_gid);
423 	(void)seteuid(rootlogin ? 0 : pwd->pw_uid);
424 	if (!*pwd->pw_dir || chdir(pwd->pw_dir) < 0) {
425 		if (login_getcapbool(lc, "requirehome", 0))
426 			refused("Home directory not available", "HOMEDIR", 1);
427 		if (chdir("/") < 0)
428 			refused("Cannot find root directory", "ROOTDIR", 1);
429 		if (!quietlog || *pwd->pw_dir)
430 			printf("No home directory.\nLogging in with home = \"/\".\n");
431 		pwd->pw_dir = strdup("/");
432 		if (pwd->pw_dir == NULL) {
433 			syslog(LOG_NOTICE, "strdup(): %m");
434 			bail(SLEEP_EXIT, 1);
435 		}
436 	}
437 	(void)seteuid(euid);
438 	(void)setegid(egid);
439 	if (!quietlog) {
440 		quietlog = access(_PATH_HUSHLOGIN, F_OK) == 0;
441 		if (!quietlog)
442 			pam_silent = 0;
443 	}
444 
445 	shell = login_getcapstr(lc, "shell", pwd->pw_shell, pwd->pw_shell);
446 	if (*pwd->pw_shell == '\0')
447 		pwd->pw_shell = strdup(_PATH_BSHELL);
448 	if (pwd->pw_shell == NULL) {
449 		syslog(LOG_NOTICE, "strdup(): %m");
450 		bail(SLEEP_EXIT, 1);
451 	}
452 	if (*shell == '\0')   /* Not overridden */
453 		shell = pwd->pw_shell;
454 	if ((shell = strdup(shell)) == NULL) {
455 		syslog(LOG_NOTICE, "strdup(): %m");
456 		bail(SLEEP_EXIT, 1);
457 	}
458 
459 	/*
460 	 * Set device protections, depending on what terminal the
461 	 * user is logged in. This feature is used on Suns to give
462 	 * console users better privacy.
463 	 */
464 	login_fbtab(tty, pwd->pw_uid, pwd->pw_gid);
465 
466 	/*
467 	 * Clear flags of the tty.  None should be set, and when the
468 	 * user sets them otherwise, this can cause the chown to fail.
469 	 * Since it isn't clear that flags are useful on character
470 	 * devices, we just clear them.
471 	 *
472 	 * We don't log in the case of EOPNOTSUPP because dev might be
473 	 * on NFS, which doesn't support chflags.
474 	 *
475 	 * We don't log in the EROFS because that means that /dev is on
476 	 * a read only file system and we assume that the permissions there
477 	 * are sane.
478 	 */
479 	if (ttyn != tname && chflags(ttyn, 0))
480 		if (errno != EOPNOTSUPP && errno != EROFS)
481 			syslog(LOG_ERR, "chflags(%s): %m", ttyn);
482 	if (ttyn != tname && chown(ttyn, pwd->pw_uid,
483 	    (gr = getgrnam(TTYGRPNAME)) ? gr->gr_gid : pwd->pw_gid))
484 		if (errno != EROFS)
485 			syslog(LOG_ERR, "chown(%s): %m", ttyn);
486 
487 #ifdef LOGALL
488 	/*
489 	 * Syslog each successful login, so we don't have to watch
490 	 * hundreds of wtmp or lastlogin files.
491 	 */
492 	if (hflag)
493 		syslog(LOG_INFO, "login from %s on %s as %s",
494 		       hostname, tty, pwd->pw_name);
495 	else
496 		syslog(LOG_INFO, "login on %s as %s",
497 		       tty, pwd->pw_name);
498 #endif
499 
500 	/*
501 	 * If fflag is on, assume caller/authenticator has logged root
502 	 * login.
503 	 */
504 	if (rootlogin && fflag == 0) {
505 		if (hflag)
506 			syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s FROM %s",
507 			    username, tty, hostname);
508 		else
509 			syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s",
510 			    username, tty);
511 	}
512 
513 	/*
514 	 * Destroy environment unless user has requested its
515 	 * preservation - but preserve TERM in all cases
516 	 */
517 	term = getenv("TERM");
518 	if (!pflag)
519 		environ = envinit;
520 	if (term != NULL)
521 		setenv("TERM", term, 0);
522 
523 	/*
524 	 * PAM modules might add supplementary groups during pam_setcred().
525 	 */
526 	if (setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETGROUP) != 0) {
527 		syslog(LOG_ERR, "setusercontext() failed - exiting");
528 		bail(NO_SLEEP_EXIT, 1);
529 	}
530 
531 	pam_err = pam_setcred(pamh, pam_silent|PAM_REINITIALIZE_CRED);
532 	if (pam_err != PAM_SUCCESS) {
533 		pam_syslog("pam_setcred()");
534 		bail(NO_SLEEP_EXIT, 1);
535 	}
536 
537 	pam_err = pam_open_session(pamh, pam_silent);
538 	if (pam_err != PAM_SUCCESS) {
539 		pam_syslog("pam_open_session()");
540 		bail(NO_SLEEP_EXIT, 1);
541 	}
542 	pam_session_established = 1;
543 
544 	/*
545 	 * We must fork() before setuid() because we need to call
546 	 * pam_close_session() as root.
547 	 */
548 	pid = fork();
549 	if (pid < 0) {
550 		err(1, "fork");
551 	} else if (pid != 0) {
552 		/*
553 		 * Parent: wait for child to finish, then clean up
554 		 * session.
555 		 *
556 		 * If we get SIGHUP or SIGTERM, clean up the session
557 		 * and exit right away. This will make the terminal
558 		 * inaccessible and send SIGHUP to the foreground
559 		 * process group.
560 		 */
561 		int status;
562 		setproctitle("-%s [pam]", getprogname());
563 		(void)sigprocmask(SIG_SETMASK, &omask, NULL);
564 		waitpid(pid, &status, 0);
565 		(void)sigprocmask(SIG_BLOCK, &mask, NULL);
566 		bail(NO_SLEEP_EXIT, 0);
567 	}
568 
569 	/*
570 	 * NOTICE: We are now in the child process!
571 	 */
572 
573 	/*
574 	 * Add any environment variables the PAM modules may have set.
575 	 */
576 	export_pam_environment();
577 
578 	/*
579 	 * We're done with PAM now; our parent will deal with the rest.
580 	 */
581 	pam_end(pamh, 0);
582 	pamh = NULL;
583 
584 	/*
585 	 * We don't need to be root anymore, so set the login name and
586 	 * the UID.
587 	 */
588 	if (setlogin(username) != 0) {
589 		syslog(LOG_ERR, "setlogin(%s): %m - exiting", username);
590 		bail(NO_SLEEP_EXIT, 1);
591 	}
592 	if (setusercontext(lc, pwd, pwd->pw_uid,
593 	    LOGIN_SETALL & ~(LOGIN_SETLOGIN|LOGIN_SETGROUP)) != 0) {
594 		syslog(LOG_ERR, "setusercontext() failed - exiting");
595 		exit(1);
596 	}
597 
598 	(void)setenv("SHELL", pwd->pw_shell, 1);
599 	(void)setenv("HOME", pwd->pw_dir, 1);
600 	/* Overwrite "term" from login.conf(5) for any known TERM */
601 	if (term == NULL && (tp = stypeof(tty)) != NULL)
602 		(void)setenv("TERM", tp, 1);
603 	else
604 		(void)setenv("TERM", TERM_UNKNOWN, 0);
605 	(void)setenv("LOGNAME", username, 1);
606 	(void)setenv("USER", username, 1);
607 	(void)setenv("PATH", rootlogin ? _PATH_STDPATH : _PATH_DEFPATH, 0);
608 
609 	if (!quietlog) {
610 		const char *cw;
611 
612 		cw = login_getcapstr(lc, "welcome", NULL, NULL);
613 		if (cw != NULL && access(cw, F_OK) == 0)
614 			motd(cw);
615 		else
616 			motd(_PATH_MOTDFILE);
617 
618 		if (login_getcapbool(lc_user, "nocheckmail", 0) == 0 &&
619 		    login_getcapbool(lc, "nocheckmail", 0) == 0) {
620 			char *cx;
621 
622 			/* $MAIL may have been set by class. */
623 			cx = getenv("MAIL");
624 			if (cx == NULL) {
625 				asprintf(&cx, "%s/%s",
626 				    _PATH_MAILDIR, pwd->pw_name);
627 			}
628 			if (cx && stat(cx, &st) == 0 && st.st_size != 0)
629 				(void)printf("You have %smail.\n",
630 				    (st.st_mtime > st.st_atime) ? "new " : "");
631 			if (getenv("MAIL") == NULL)
632 				free(cx);
633 		}
634 	}
635 
636 	login_close(lc_user);
637 	login_close(lc);
638 
639 	sa.sa_handler = SIG_DFL;
640 	(void)sigaction(SIGALRM, &sa, NULL);
641 	(void)sigaction(SIGQUIT, &sa, NULL);
642 	(void)sigaction(SIGINT, &sa, NULL);
643 	(void)sigaction(SIGTERM, &sa, NULL);
644 	(void)sigaction(SIGHUP, &sa, NULL);
645 	sa.sa_handler = SIG_IGN;
646 	(void)sigaction(SIGTSTP, &sa, NULL);
647 	(void)sigprocmask(SIG_SETMASK, &omask, NULL);
648 
649 	/*
650 	 * Login shells have a leading '-' in front of argv[0]
651 	 */
652 	p = strrchr(pwd->pw_shell, '/');
653 	if (asprintf(&arg0, "-%s", p ? p + 1 : pwd->pw_shell) >= MAXPATHLEN) {
654 		syslog(LOG_ERR, "user: %s: shell exceeds maximum pathname size",
655 		    username);
656 		errx(1, "shell exceeds maximum pathname size");
657 	} else if (arg0 == NULL) {
658 		err(1, "asprintf()");
659 	}
660 
661 	execlp(shell, arg0, (char *)0);
662 	err(1, "%s", shell);
663 
664 	/*
665 	 * That's it, folks!
666 	 */
667 }
668 
669 /*
670  * Attempt to authenticate the user using PAM.  Returns 0 if the user is
671  * authenticated, or 1 if not authenticated.  If some sort of PAM system
672  * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
673  * function returns -1.  This can be used as an indication that we should
674  * fall back to a different authentication mechanism.
675  */
676 static int
677 auth_pam(void)
678 {
679 	const char *tmpl_user;
680 	const void *item;
681 	int rval;
682 
683 	pam_err = pam_authenticate(pamh, pam_silent);
684 	switch (pam_err) {
685 
686 	case PAM_SUCCESS:
687 		/*
688 		 * With PAM we support the concept of a "template"
689 		 * user.  The user enters a login name which is
690 		 * authenticated by PAM, usually via a remote service
691 		 * such as RADIUS or TACACS+.  If authentication
692 		 * succeeds, a different but related "template" name
693 		 * is used for setting the credentials, shell, and
694 		 * home directory.  The name the user enters need only
695 		 * exist on the remote authentication server, but the
696 		 * template name must be present in the local password
697 		 * database.
698 		 *
699 		 * This is supported by two various mechanisms in the
700 		 * individual modules.  However, from the application's
701 		 * point of view, the template user is always passed
702 		 * back as a changed value of the PAM_USER item.
703 		 */
704 		pam_err = pam_get_item(pamh, PAM_USER, &item);
705 		if (pam_err == PAM_SUCCESS) {
706 			tmpl_user = (const char *)item;
707 			if (strcmp(username, tmpl_user) != 0) {
708 				(void)getpwnam_r(tmpl_user, &pwres, pwbuf,
709 				    sizeof(pwbuf), &pwd);
710 			}
711 		} else {
712 			pam_syslog("pam_get_item(PAM_USER)");
713 		}
714 		rval = 0;
715 		break;
716 
717 	case PAM_AUTH_ERR:
718 	case PAM_USER_UNKNOWN:
719 	case PAM_MAXTRIES:
720 		rval = 1;
721 		break;
722 
723 	default:
724 		pam_syslog("pam_authenticate()");
725 		rval = -1;
726 		break;
727 	}
728 
729 	if (rval == 0) {
730 		pam_err = pam_acct_mgmt(pamh, pam_silent);
731 		switch (pam_err) {
732 		case PAM_SUCCESS:
733 			break;
734 		case PAM_NEW_AUTHTOK_REQD:
735 			pam_err = pam_chauthtok(pamh,
736 			    pam_silent|PAM_CHANGE_EXPIRED_AUTHTOK);
737 			if (pam_err != PAM_SUCCESS) {
738 				pam_syslog("pam_chauthtok()");
739 				rval = 1;
740 			}
741 			break;
742 		default:
743 			pam_syslog("pam_acct_mgmt()");
744 			rval = 1;
745 			break;
746 		}
747 	}
748 
749 	if (rval != 0) {
750 		pam_end(pamh, pam_err);
751 		pamh = NULL;
752 	}
753 	return (rval);
754 }
755 
756 /*
757  * Export any environment variables PAM modules may have set
758  */
759 static void
760 export_pam_environment(void)
761 {
762 	char **pam_env;
763 	char **pp;
764 
765 	pam_env = pam_getenvlist(pamh);
766 	if (pam_env != NULL) {
767 		for (pp = pam_env; *pp != NULL; pp++) {
768 			(void)export(*pp);
769 			free(*pp);
770 		}
771 	}
772 }
773 
774 /*
775  * Perform sanity checks on an environment variable:
776  * - Make sure there is an '=' in the string.
777  * - Make sure the string doesn't run on too long.
778  * - Do not export certain variables.  This list was taken from the
779  *   Solaris pam_putenv(3) man page.
780  * Then export it.
781  */
782 static int
783 export(const char *s)
784 {
785 	static const char *noexport[] = {
786 		"SHELL", "HOME", "LOGNAME", "MAIL", "CDPATH",
787 		"IFS", "PATH", NULL
788 	};
789 	char *p;
790 	const char **pp;
791 	size_t n;
792 	int rv;
793 
794 	if (strlen(s) > 1024 || (p = strchr(s, '=')) == NULL)
795 		return (0);
796 	if (strncmp(s, "LD_", 3) == 0)
797 		return (0);
798 	for (pp = noexport; *pp != NULL; pp++) {
799 		n = strlen(*pp);
800 		if (s[n] == '=' && strncmp(s, *pp, n) == 0)
801 			return (0);
802 	}
803 	*p = '\0';
804 	rv = setenv(s, p + 1, 1);
805 	*p = '=';
806 	if (rv == -1)
807 		return (0);
808 	return (1);
809 }
810 
811 static void
812 usage(void)
813 {
814 
815 	(void)fprintf(stderr, "usage: login [-fp] [-h hostname] [username]\n");
816 	exit(1);
817 }
818 
819 /*
820  * Prompt user and read login name from stdin.
821  */
822 static char *
823 getloginname(void)
824 {
825 	char *nbuf, *p;
826 	int ch;
827 
828 	nbuf = malloc(MAXLOGNAME);
829 	if (nbuf == NULL)
830 		err(1, "malloc()");
831 	do {
832 		(void)printf("%s", prompt);
833 		for (p = nbuf; (ch = getchar()) != '\n'; ) {
834 			if (ch == EOF) {
835 				badlogin(username);
836 				bail(NO_SLEEP_EXIT, 0);
837 			}
838 			if (p < nbuf + MAXLOGNAME - 1)
839 				*p++ = ch;
840 		}
841 	} while (p == nbuf);
842 
843 	*p = '\0';
844 	if (nbuf[0] == '-') {
845 		pam_silent = 0;
846 		memmove(nbuf, nbuf + 1, strlen(nbuf));
847 	} else {
848 		pam_silent = PAM_SILENT;
849 	}
850 	return nbuf;
851 }
852 
853 /*
854  * SIGINT handler for motd().
855  */
856 static volatile int motdinterrupt;
857 static void
858 sigint(int signo __unused)
859 {
860 	motdinterrupt = 1;
861 }
862 
863 /*
864  * Display the contents of a file (such as /etc/motd).
865  */
866 static int
867 motd(const char *motdfile)
868 {
869 	struct sigaction newint, oldint;
870 	FILE *f;
871 	int ch;
872 
873 	if ((f = fopen(motdfile, "r")) == NULL)
874 		return (-1);
875 	motdinterrupt = 0;
876 	newint.sa_handler = sigint;
877 	newint.sa_flags = 0;
878 	sigfillset(&newint.sa_mask);
879 	sigaction(SIGINT, &newint, &oldint);
880 	while ((ch = fgetc(f)) != EOF && !motdinterrupt)
881 		putchar(ch);
882 	sigaction(SIGINT, &oldint, NULL);
883 	if (ch != EOF || ferror(f)) {
884 		fclose(f);
885 		return (-1);
886 	}
887 	fclose(f);
888 	return (0);
889 }
890 
891 /*
892  * SIGALRM handler, to enforce login prompt timeout.
893  *
894  * XXX This can potentially confuse the hell out of PAM.  We should
895  * XXX instead implement a conversation function that returns
896  * XXX PAM_CONV_ERR when interrupted by a signal, and have the signal
897  * XXX handler just set a flag.
898  */
899 static void
900 timedout(int signo __unused)
901 {
902 
903 	longjmp(timeout_buf, signo);
904 }
905 
906 static void
907 badlogin(char *name)
908 {
909 
910 	if (failures == 0)
911 		return;
912 	if (hflag) {
913 		syslog(LOG_NOTICE, "%d LOGIN FAILURE%s FROM %s",
914 		    failures, failures > 1 ? "S" : "", hostname);
915 		syslog(LOG_AUTHPRIV|LOG_NOTICE,
916 		    "%d LOGIN FAILURE%s FROM %s, %s",
917 		    failures, failures > 1 ? "S" : "", hostname, name);
918 	} else {
919 		syslog(LOG_NOTICE, "%d LOGIN FAILURE%s ON %s",
920 		    failures, failures > 1 ? "S" : "", tty);
921 		syslog(LOG_AUTHPRIV|LOG_NOTICE,
922 		    "%d LOGIN FAILURE%s ON %s, %s",
923 		    failures, failures > 1 ? "S" : "", tty, name);
924 	}
925 	failures = 0;
926 }
927 
928 const char *
929 stypeof(char *ttyid)
930 {
931 	struct ttyent *t;
932 
933 	if (ttyid != NULL && *ttyid != '\0') {
934 		t = getttynam(ttyid);
935 		if (t != NULL && t->ty_type != NULL)
936 			return (t->ty_type);
937 	}
938 	return (NULL);
939 }
940 
941 static void
942 refused(const char *msg, const char *rtype, int lout)
943 {
944 
945 	if (msg != NULL)
946 	    printf("%s.\n", msg);
947 	if (hflag)
948 		syslog(LOG_NOTICE, "LOGIN %s REFUSED (%s) FROM %s ON TTY %s",
949 		    pwd->pw_name, rtype, hostname, tty);
950 	else
951 		syslog(LOG_NOTICE, "LOGIN %s REFUSED (%s) ON TTY %s",
952 		    pwd->pw_name, rtype, tty);
953 	if (lout)
954 		bail(SLEEP_EXIT, 1);
955 }
956 
957 /*
958  * Log a PAM error
959  */
960 static void
961 pam_syslog(const char *msg)
962 {
963 	syslog(LOG_ERR, "%s: %s", msg, pam_strerror(pamh, pam_err));
964 }
965 
966 /*
967  * Shut down PAM
968  */
969 static void
970 pam_cleanup(void)
971 {
972 
973 	if (pamh != NULL) {
974 		if (pam_session_established) {
975 			pam_err = pam_close_session(pamh, 0);
976 			if (pam_err != PAM_SUCCESS)
977 				pam_syslog("pam_close_session()");
978 		}
979 		pam_session_established = 0;
980 		if (pam_cred_established) {
981 			pam_err = pam_setcred(pamh, pam_silent|PAM_DELETE_CRED);
982 			if (pam_err != PAM_SUCCESS)
983 				pam_syslog("pam_setcred()");
984 		}
985 		pam_cred_established = 0;
986 		pam_end(pamh, pam_err);
987 		pamh = NULL;
988 	}
989 }
990 
991 static void
992 bail_internal(int sec, int eval, int signo)
993 {
994 	struct sigaction sa;
995 
996 	pam_cleanup();
997 #ifdef USE_BSM_AUDIT
998 	if (pwd != NULL)
999 		audit_logout();
1000 #endif
1001 	(void)sleep(sec);
1002 	if (signo == 0)
1003 		exit(eval);
1004 	else {
1005 		sa.sa_handler = SIG_DFL;
1006 		sa.sa_flags = 0;
1007 		(void)sigemptyset(&sa.sa_mask);
1008 		(void)sigaction(signo, &sa, NULL);
1009 		(void)sigaddset(&sa.sa_mask, signo);
1010 		(void)sigprocmask(SIG_UNBLOCK, &sa.sa_mask, NULL);
1011 		raise(signo);
1012 		exit(128 + signo);
1013 	}
1014 }
1015 
1016 /*
1017  * Exit, optionally after sleeping a few seconds
1018  */
1019 static void
1020 bail(int sec, int eval)
1021 {
1022 	bail_internal(sec, eval, 0);
1023 }
1024 
1025 /*
1026  * Exit because of a signal.
1027  * This is not async-signal safe, so only call async-signal safe functions
1028  * while the signal is unmasked.
1029  */
1030 static void
1031 bail_sig(int signo)
1032 {
1033 	bail_internal(NO_SLEEP_EXIT, 0, signo);
1034 }
1035