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