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