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