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