Home | History | Annotate | Line # | Download | only in login
login_pam.c revision 1.4
      1 /*     $NetBSD: login_pam.c,v 1.4 2005/03/03 02:06:16 christos Exp $       */
      2 
      3 /*-
      4  * Copyright (c) 1980, 1987, 1988, 1991, 1993, 1994
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. Neither the name of the University nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 #include <sys/cdefs.h>
     33 #ifndef lint
     34 __COPYRIGHT(
     35 "@(#) Copyright (c) 1980, 1987, 1988, 1991, 1993, 1994\n\
     36 	The Regents of the University of California.  All rights reserved.\n");
     37 #endif /* not lint */
     38 
     39 #ifndef lint
     40 #if 0
     41 static char sccsid[] = "@(#)login.c	8.4 (Berkeley) 4/2/94";
     42 #endif
     43 __RCSID("$NetBSD: login_pam.c,v 1.4 2005/03/03 02:06:16 christos Exp $");
     44 #endif /* not lint */
     45 
     46 /*
     47  * login [ name ]
     48  * login -h hostname	(for telnetd, etc.)
     49  * login -f name	(for pre-authenticated login: datakit, xterm, etc.)
     50  */
     51 
     52 #include <sys/param.h>
     53 #include <sys/stat.h>
     54 #include <sys/time.h>
     55 #include <sys/resource.h>
     56 #include <sys/file.h>
     57 #include <sys/wait.h>
     58 #include <sys/socket.h>
     59 
     60 #include <err.h>
     61 #include <errno.h>
     62 #include <grp.h>
     63 #include <pwd.h>
     64 #include <setjmp.h>
     65 #include <signal.h>
     66 #include <stdio.h>
     67 #include <stdlib.h>
     68 #include <string.h>
     69 #include <syslog.h>
     70 #include <time.h>
     71 #include <ttyent.h>
     72 #include <tzfile.h>
     73 #include <unistd.h>
     74 #include <util.h>
     75 #include <login_cap.h>
     76 #include <vis.h>
     77 
     78 #include <security/pam_appl.h>
     79 #include <security/openpam.h>
     80 
     81 #include "pathnames.h"
     82 
     83 void	 badlogin (char *);
     84 static void	 update_db (int);
     85 void	 getloginname (void);
     86 int	 main (int, char *[]);
     87 void	 motd (char *);
     88 int	 rootterm (char *);
     89 void	 sigint (int);
     90 void	 sleepexit (int);
     91 const	 char *stypeof (const char *);
     92 void	 timedout (int);
     93 void	 decode_ss (const char *);
     94 void	 usage (void);
     95 
     96 static struct pam_conv pamc = { openpam_ttyconv, NULL };
     97 
     98 #define	TTYGRPNAME	"tty"		/* name of group to own ttys */
     99 
    100 #define DEFAULT_BACKOFF 3
    101 #define DEFAULT_RETRIES 10
    102 
    103 /*
    104  * This bounds the time given to login.  Not a define so it can
    105  * be patched on machines where it's too small.
    106  */
    107 u_int	timeout = 300;
    108 
    109 struct	passwd *pwd;
    110 struct	group *gr;
    111 int	failures, have_ss;
    112 char	term[64], *envinit[1], *hostname, *username, *tty, *nested;
    113 struct timeval now;
    114 struct sockaddr_storage ss;
    115 
    116 extern const char copyrightstr[];
    117 
    118 int
    119 main(int argc, char *argv[])
    120 {
    121 	extern char **environ;
    122 	struct stat st;
    123 	int ask, ch, cnt, fflag, hflag, pflag, sflag, quietlog, rootlogin;
    124 	int auth_passed;
    125 	int Fflag;
    126 	uid_t uid, saved_uid;
    127 	gid_t saved_gid, saved_gids[NGROUPS_MAX];
    128 	int nsaved_gids;
    129 	char *domain, *p, *ttyn, *pwprompt;
    130 	char tbuf[MAXPATHLEN + 2], tname[sizeof(_PATH_TTY) + 10];
    131 	char localhost[MAXHOSTNAMELEN + 1];
    132 	int need_chpass, require_chpass;
    133 	int login_retries = DEFAULT_RETRIES,
    134 	    login_backoff = DEFAULT_BACKOFF;
    135 	char *shell = NULL;
    136 	login_cap_t *lc = NULL;
    137 	pam_handle_t *pamh = NULL;
    138 	int pam_err;
    139 	void *oint;
    140 	void *oabrt;
    141 	const void *newuser;
    142 	int pam_silent = PAM_SILENT;
    143 	pid_t xpid, pid;
    144 	int status;
    145 	char *saved_term;
    146 	char **pamenv;
    147 
    148 	tbuf[0] = '\0';
    149 	pwprompt = NULL;
    150 	nested = NULL;
    151 	need_chpass = require_chpass = 0;
    152 
    153 	(void)signal(SIGALRM, timedout);
    154 	(void)alarm(timeout);
    155 	(void)signal(SIGQUIT, SIG_IGN);
    156 	(void)signal(SIGINT, SIG_IGN);
    157 	(void)setpriority(PRIO_PROCESS, 0, 0);
    158 
    159 	openlog("login", 0, LOG_AUTH);
    160 
    161 	/*
    162 	 * -p is used by getty to tell login not to destroy the environment
    163 	 * -f is used to skip a second login authentication
    164 	 * -h is used by other servers to pass the name of the remote host to
    165 	 *    login so that it may be placed in utmp/utmpx and wtmp/wtmpx
    166 	 * -a in addition to -h, a server my supply -a to pass the actual
    167 	 *    server address.
    168 	 * -s is used to force use of S/Key or equivalent.
    169 	 */
    170 	domain = NULL;
    171 	if (gethostname(localhost, sizeof(localhost)) < 0)
    172 		syslog(LOG_ERR, "couldn't get local hostname: %m");
    173 	else
    174 		domain = strchr(localhost, '.');
    175 	localhost[sizeof(localhost) - 1] = '\0';
    176 
    177 	Fflag = fflag = hflag = pflag = sflag = 0;
    178 	have_ss = 0;
    179 	uid = getuid();
    180 	while ((ch = getopt(argc, argv, "a:Ffh:ps")) != -1)
    181 		switch (ch) {
    182 		case 'a':
    183 			if (uid)
    184 				errx(1, "-a option: %s", strerror(EPERM));
    185 			decode_ss(optarg);
    186 #ifdef notdef
    187 			(void)sockaddr_snprintf(optarg,
    188 			    sizeof(struct sockaddr_storage), "%a", (void *)&ss);
    189 #endif
    190 			break;
    191 		case 'F':
    192 			Fflag = 1;
    193 			/* FALLTHROUGH */
    194 		case 'f':
    195 			fflag = 1;
    196 			break;
    197 		case 'h':
    198 			if (uid)
    199 				errx(1, "-h option: %s", strerror(EPERM));
    200 			hflag = 1;
    201 			if (domain && (p = strchr(optarg, '.')) != NULL &&
    202 			    strcasecmp(p, domain) == 0)
    203 				*p = '\0';
    204 			hostname = optarg;
    205 			break;
    206 		case 'p':
    207 			pflag = 1;
    208 			break;
    209 		case 's':
    210 			sflag = 1;
    211 			break;
    212 		default:
    213 		case '?':
    214 			usage();
    215 			break;
    216 		}
    217 
    218 	setproctitle(NULL);
    219 	argc -= optind;
    220 	argv += optind;
    221 
    222 	if (*argv) {
    223 		username = *argv;
    224 		ask = 0;
    225 	} else
    226 		ask = 1;
    227 
    228 #ifdef F_CLOSEM
    229 	(void)fcntl(3, F_CLOSEM, 0);
    230 #else
    231 	for (cnt = getdtablesize(); cnt > 2; cnt--)
    232 		(void)close(cnt);
    233 #endif
    234 
    235 	ttyn = ttyname(STDIN_FILENO);
    236 	if (ttyn == NULL || *ttyn == '\0') {
    237 		(void)snprintf(tname, sizeof(tname), "%s??", _PATH_TTY);
    238 		ttyn = tname;
    239 	}
    240 	if ((tty = strstr(ttyn, "/pts/")) != NULL)
    241 		++tty;
    242 	else if ((tty = strrchr(ttyn, '/')) != NULL)
    243 		++tty;
    244 	else
    245 		tty = ttyn;
    246 
    247 	if (issetugid()) {
    248 		nested = strdup(user_from_uid(getuid(), 0));
    249 		if (nested == NULL) {
    250                 	syslog(LOG_ERR, "strdup: %m");
    251                 	sleepexit(1);
    252 		}
    253 	}
    254 
    255 	/* Get "login-retries" and "login-backoff" from default class */
    256 	if ((lc = login_getclass(NULL)) != NULL) {
    257 		login_retries = (int)login_getcapnum(lc, "login-retries",
    258 		    DEFAULT_RETRIES, DEFAULT_RETRIES);
    259 		login_backoff = (int)login_getcapnum(lc, "login-backoff",
    260 		    DEFAULT_BACKOFF, DEFAULT_BACKOFF);
    261 		login_close(lc);
    262 		lc = NULL;
    263 	}
    264 
    265 
    266 	for (cnt = 0;; ask = 1) {
    267 		if (ask) {
    268 			fflag = 0;
    269 			getloginname();
    270 		}
    271 		rootlogin = 0;
    272 		auth_passed = 0;
    273 		if (strlen(username) > MAXLOGNAME)
    274 			username[MAXLOGNAME] = '\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(tbuf, username)) {
    282 			if (failures > (pwd ? 0 : 1))
    283 				badlogin(tbuf);
    284 			failures = 0;
    285 		}
    286 
    287 #define PAM_END(msg) do { 						\
    288 	syslog(LOG_ERR, "%s: %s", msg, pam_strerror(pamh, pam_err)); 	\
    289 	warnx("%s: %s", msg, pam_strerror(pamh, pam_err));		\
    290 	pam_end(pamh, pam_err);						\
    291 	sleepexit(1); 							\
    292 } while (/*CONSTCOND*/0)
    293 
    294 		pam_err = pam_start("login", username, &pamc, &pamh);
    295 		if (pam_err != PAM_SUCCESS) {
    296 			if (pamh != NULL)
    297 				PAM_END("pam_start");
    298 			/* Things went really bad... */
    299 			syslog(LOG_ERR, "pam_start failed: %s",
    300 			    pam_strerror(pamh, pam_err));
    301 			errx(1, "pam_start failed");
    302 		}
    303 
    304 #define PAM_SET_ITEM(item, var)	do {					\
    305 	pam_err = pam_set_item(pamh, (item), (var));			\
    306 	if (pam_err != PAM_SUCCESS)					\
    307 		PAM_END("pam_set_item(" # item ")");			\
    308 } while (/*CONSTCOND*/0)
    309 
    310 		/*
    311 		 * Fill hostname tty, and nested user
    312 		 */
    313 		PAM_SET_ITEM(PAM_RHOST, hostname);
    314 		PAM_SET_ITEM(PAM_TTY, tty);
    315 		if (nested)
    316 			PAM_SET_ITEM(PAM_NUSER, nested);
    317 		if (have_ss)
    318 			PAM_SET_ITEM(PAM_SOCKADDR, &ss);
    319 
    320 		pwd = getpwnam(username);
    321 
    322 		/*
    323 		 * Establish the class now, before we might goto
    324 		 * within the next block. pwd can be NULL since it
    325 		 * falls back to the "default" class if it is.
    326 		 */
    327 		lc = login_getclass(pwd ? pwd->pw_class : NULL);
    328 
    329 		/*
    330 		 * if we have a valid account name, and it doesn't have a
    331 		 * password, or the -f option was specified and the caller
    332 		 * is root or the caller isn't changing their uid, don't
    333 		 * authenticate.
    334 		 */
    335 		if (pwd) {
    336 			if (pwd->pw_uid == 0)
    337 				rootlogin = 1;
    338 
    339 			if (fflag && (uid == 0 || uid == pwd->pw_uid)) {
    340 				/* already authenticated */
    341 				auth_passed = 1;
    342 				goto skip_auth;
    343 			}
    344 		}
    345 
    346 		(void)setpriority(PRIO_PROCESS, 0, -4);
    347 
    348 		switch(pam_err = pam_authenticate(pamh, pam_silent)) {
    349 		case PAM_SUCCESS:
    350 			/*
    351 			 * PAM can change the user, refresh
    352 			 * username, pwd, and lc.
    353 			 */
    354 			pam_err = pam_get_item(pamh, PAM_USER, &newuser);
    355 			if (pam_err != PAM_SUCCESS)
    356 				PAM_END("pam_get_item(PAM_USER)");
    357 
    358 			username = (char *)newuser;
    359 			pwd = getpwnam(username);
    360 			lc = login_getpwclass(pwd);
    361 			auth_passed = 1;
    362 
    363 			switch (pam_err = pam_acct_mgmt(pamh, pam_silent)) {
    364 			case PAM_SUCCESS:
    365 				break;
    366 
    367 			case PAM_NEW_AUTHTOK_REQD:
    368 				pam_err = pam_chauthtok(pamh,
    369 				    pam_silent|PAM_CHANGE_EXPIRED_AUTHTOK);
    370 
    371 				if (pam_err != PAM_SUCCESS)
    372 					PAM_END("pam_chauthtok");
    373 				break;
    374 
    375 			default:
    376 				PAM_END("pam_acct_mgmt");
    377 				break;
    378 			}
    379 			break;
    380 
    381 		case PAM_AUTH_ERR:
    382 		case PAM_USER_UNKNOWN:
    383 		case PAM_MAXTRIES:
    384 			auth_passed = 0;
    385 			break;
    386 
    387 		default:
    388 			PAM_END("pam_authenticate");
    389 			break;
    390 		}
    391 
    392 		(void)setpriority(PRIO_PROCESS, 0, 0);
    393 
    394 skip_auth:
    395 		/*
    396 		 * If the user exists and authentication passed,
    397 		 * get out of the loop and login the user.
    398 		 */
    399 		if (pwd && auth_passed)
    400 			break;
    401 
    402 		(void)printf("Login incorrect\n");
    403 		failures++;
    404 		cnt++;
    405 		/* we allow 10 tries, but after 3 we start backing off */
    406 		if (cnt > login_backoff) {
    407 			if (cnt >= login_retries) {
    408 				badlogin(username);
    409 				pam_end(pamh, PAM_SUCCESS);
    410 				sleepexit(1);
    411 			}
    412 			sleep((u_int)((cnt - 3) * 5));
    413 		}
    414 	}
    415 
    416 	/* committed to login -- turn off timeout */
    417 	(void)alarm((u_int)0);
    418 
    419 	endpwent();
    420 
    421         quietlog = login_getcapbool(lc, "hushlogin", 0);
    422 
    423 	/*
    424 	 * Temporarily give up special privileges so we can change
    425 	 * into NFS-mounted homes that are exported for non-root
    426 	 * access and have mode 7x0
    427 	 */
    428 	saved_uid = geteuid();
    429 	saved_gid = getegid();
    430 	nsaved_gids = getgroups(NGROUPS_MAX, saved_gids);
    431 
    432 	(void)setegid(pwd->pw_gid);
    433 	initgroups(username, pwd->pw_gid);
    434 	(void)seteuid(pwd->pw_uid);
    435 
    436 	if (chdir(pwd->pw_dir) != 0) {
    437                 if (login_getcapbool(lc, "requirehome", 0)) {
    438 			(void)printf("Home directory %s required\n",
    439 			    pwd->pw_dir);
    440 			pam_end(pamh, PAM_SUCCESS);
    441                         exit(1);
    442 		}
    443 
    444 		(void)printf("No home directory %s!\n", pwd->pw_dir);
    445 		if (chdir("/")) {
    446 			pam_end(pamh, PAM_SUCCESS);
    447 			exit(0);
    448 		}
    449 		pwd->pw_dir = "/";
    450 		(void)printf("Logging in with home = \"/\".\n");
    451 	}
    452 
    453 	if (!quietlog) {
    454 		quietlog = access(_PATH_HUSHLOGIN, F_OK) == 0;
    455 		pam_silent = 0;
    456 	}
    457 
    458 	/* regain special privileges */
    459 	setegid(saved_gid);
    460 	setgroups(nsaved_gids, saved_gids);
    461 	seteuid(saved_uid);
    462 
    463 	(void)chown(ttyn, pwd->pw_uid,
    464 	    (gr = getgrnam(TTYGRPNAME)) ? gr->gr_gid : pwd->pw_gid);
    465 
    466 	if (ttyaction(ttyn, "login", pwd->pw_name))
    467 		(void)printf("Warning: ttyaction failed.\n");
    468 
    469 	/* Nothing else left to fail -- really log in. */
    470         update_db(quietlog);
    471 
    472 	if (nested == NULL && setusercontext(lc, pwd, pwd->pw_uid,
    473 	    LOGIN_SETLOGIN) != 0) {
    474 		syslog(LOG_ERR, "setusercontext failed");
    475 		pam_end(pamh, PAM_SUCCESS);
    476 		exit(1);
    477 	}
    478 
    479 	if (tty[sizeof("tty")-1] == 'd')
    480 		syslog(LOG_INFO, "DIALUP %s, %s", tty, pwd->pw_name);
    481 
    482 	/* If fflag is on, assume caller/authenticator has logged root login. */
    483 	if (rootlogin && fflag == 0) {
    484 		if (hostname)
    485 			syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s FROM %s",
    486 			    username, tty, hostname);
    487 		else
    488 			syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s",
    489 			    username, tty);
    490 	}
    491 
    492 	/*
    493 	 * Establish groups
    494 	 */
    495 	if (setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETGROUP) != 0) {
    496 		syslog(LOG_ERR, "setusercontext failed");
    497 		pam_end(pamh, PAM_SUCCESS);
    498 		exit(1);
    499 	}
    500 
    501 	pam_err = pam_setcred(pamh, pam_silent|PAM_ESTABLISH_CRED);
    502 	if (pam_err != PAM_SUCCESS)
    503 		PAM_END("pam_setcred");
    504 
    505 	pam_err = pam_open_session(pamh, pam_silent);
    506 	if (pam_err != PAM_SUCCESS)
    507 		PAM_END("pam_open_session");
    508 
    509 	/*
    510 	 * Fork because we need to call pam_closesession as root.
    511 	 * Make sure signals cannot kill the parent.
    512 	 * This is copied from crontab(8), which has to
    513          * cope with a similar situation.
    514 	 */
    515 	oint = signal(SIGINT, SIG_IGN);
    516 	oabrt = signal(SIGABRT, SIG_IGN);
    517 
    518 	switch(pid = fork()) {
    519 	case -1:
    520 		pam_err = pam_close_session(pamh, 0);
    521 		if (pam_err != PAM_SUCCESS) {
    522 			syslog(LOG_ERR, "pam_close_session: %s",
    523 			    pam_strerror(pamh, pam_err));
    524 			warnx("pam_close_session: %s",
    525 			    pam_strerror(pamh, pam_err));
    526 		}
    527 		syslog(LOG_ERR, "fork failed: %m");
    528 		warn("fork failed");
    529 		pam_end(pamh, pam_err);
    530 		exit(1);
    531 		break;
    532 
    533 	case 0: /* Child */
    534 		break;
    535 
    536 	default:
    537 		/*
    538 		 * Parent: wait for the child to terminate
    539 		 * and call pam_close_session.
    540 		 */
    541 		if ((xpid = waitpid(pid, &status, 0)) != pid) {
    542 			pam_err = pam_close_session(pamh, 0);
    543 			if (pam_err != PAM_SUCCESS) {
    544 				syslog(LOG_ERR,
    545 				    "pam_close_session: %s",
    546 				    pam_strerror(pamh, pam_err));
    547 				warnx("pam_close_session: %s",
    548 				    pam_strerror(pamh, pam_err));
    549 			}
    550 			pam_end(pamh, pam_err);
    551 			if (xpid != -1)
    552 				warnx("wrong PID: %d != %d", pid, xpid);
    553 			else
    554 				warn("wait for pid %d failed", pid);
    555 			exit(1);
    556 		}
    557 
    558 		(void)signal(SIGINT, oint);
    559 		(void)signal(SIGABRT, oabrt);
    560 		if ((pam_err = pam_close_session(pamh, 0)) != PAM_SUCCESS) {
    561 			syslog(LOG_ERR, "pam_close_session: %s",
    562 			    pam_strerror(pamh, pam_err));
    563 			warnx("pam_close_session: %s",
    564 			    pam_strerror(pamh, pam_err));
    565 		}
    566 		pam_end(pamh, PAM_SUCCESS);
    567 		exit(0);
    568 		break;
    569 	}
    570 
    571 	/*
    572 	 * The child: starting here, we don't have to care about
    573 	 * handling PAM issues if we exit, the parent will do the
    574 	 * job when we exit.
    575          *
    576 	 * Destroy environment unless user has requested its preservation.
    577 	 * Try to preserve TERM anyway.
    578 	 */
    579 	saved_term = getenv("TERM");
    580 	if (!pflag) {
    581 		environ = envinit;
    582 		if (saved_term)
    583 			setenv("TERM", saved_term, 0);
    584 	}
    585 
    586 	if (*pwd->pw_shell == '\0')
    587 		pwd->pw_shell = _PATH_BSHELL;
    588 
    589 	shell = login_getcapstr(lc, "shell", pwd->pw_shell, pwd->pw_shell);
    590 	if (*shell == '\0')
    591 		shell = pwd->pw_shell;
    592 
    593 	if ((pwd->pw_shell = strdup(shell)) == NULL) {
    594 		syslog(LOG_ERR, "Cannot alloc mem");
    595 		exit(1);
    596 	}
    597 
    598 	(void)setenv("HOME", pwd->pw_dir, 1);
    599 	(void)setenv("SHELL", pwd->pw_shell, 1);
    600 	if (term[0] == '\0') {
    601 		char *tt = (char *)stypeof(tty);
    602 
    603 		if (tt == NULL)
    604 			tt = login_getcapstr(lc, "term", NULL, NULL);
    605 
    606 		/* unknown term -> "su" */
    607 		(void)strlcpy(term, tt != NULL ? tt : "su", sizeof(term));
    608 	}
    609 	(void)setenv("TERM", term, 0);
    610 	(void)setenv("LOGNAME", pwd->pw_name, 1);
    611 	(void)setenv("USER", pwd->pw_name, 1);
    612 
    613 	/*
    614 	 * Add PAM environement
    615 	 */
    616 	if ((pamenv = pam_getenvlist(pamh)) != NULL) {
    617 		char **envitem;
    618 
    619 		for (envitem = pamenv; *envitem; envitem++) {
    620 			putenv(*envitem);
    621 			free(*envitem);
    622 		}
    623 
    624 		free(pamenv);
    625 	}
    626 
    627 	/* This drops root privs */
    628 	if (setusercontext(lc, pwd, pwd->pw_uid,
    629 	    (LOGIN_SETALL & ~LOGIN_SETLOGIN)) != 0) {
    630 		syslog(LOG_ERR, "setusercontext failed");
    631 		exit(1);
    632 	}
    633 
    634 	if (!quietlog) {
    635 		char *fname;
    636 
    637 		fname = login_getcapstr(lc, "copyright", NULL, NULL);
    638 		if (fname != NULL && access(fname, F_OK) == 0)
    639 			motd(fname);
    640 		else
    641 			(void)printf("%s", copyrightstr);
    642 
    643                 fname = login_getcapstr(lc, "welcome", NULL, NULL);
    644                 if (fname == NULL || access(fname, F_OK) != 0)
    645                         fname = _PATH_MOTDFILE;
    646                 motd(fname);
    647 
    648 		(void)snprintf(tbuf,
    649 		    sizeof(tbuf), "%s/%s", _PATH_MAILDIR, pwd->pw_name);
    650 		if (stat(tbuf, &st) == 0 && st.st_size != 0)
    651 			(void)printf("You have %smail.\n",
    652 			    (st.st_mtime > st.st_atime) ? "new " : "");
    653 	}
    654 
    655 	login_close(lc);
    656 
    657 	(void)signal(SIGALRM, SIG_DFL);
    658 	(void)signal(SIGQUIT, SIG_DFL);
    659 	(void)signal(SIGINT, SIG_DFL);
    660 	(void)signal(SIGTSTP, SIG_IGN);
    661 
    662 	tbuf[0] = '-';
    663 	(void)strlcpy(tbuf + 1, (p = strrchr(pwd->pw_shell, '/')) ?
    664 	    p + 1 : pwd->pw_shell, sizeof(tbuf) - 1);
    665 
    666 	execlp(pwd->pw_shell, tbuf, 0);
    667 	err(1, "%s", pwd->pw_shell);
    668 }
    669 
    670 #define	NBUFSIZ		(MAXLOGNAME + 1)
    671 
    672 
    673 void
    674 getloginname(void)
    675 {
    676 	int ch;
    677 	char *p;
    678 	static char nbuf[NBUFSIZ];
    679 
    680 	for (;;) {
    681 		(void)printf("login: ");
    682 		for (p = nbuf; (ch = getchar()) != '\n'; ) {
    683 			if (ch == EOF) {
    684 				badlogin(username);
    685 				exit(0);
    686 			}
    687 			if (p < nbuf + (NBUFSIZ - 1))
    688 				*p++ = ch;
    689 		}
    690 		if (p > nbuf) {
    691 			if (nbuf[0] == '-')
    692 				(void)fprintf(stderr,
    693 				    "login names may not start with '-'.\n");
    694 			else {
    695 				*p = '\0';
    696 				username = nbuf;
    697 				break;
    698 			}
    699 		}
    700 	}
    701 }
    702 
    703 int
    704 rootterm(char *ttyn)
    705 {
    706 	struct ttyent *t;
    707 
    708 	return ((t = getttynam(ttyn)) && t->ty_status & TTY_SECURE);
    709 }
    710 
    711 jmp_buf motdinterrupt;
    712 
    713 void
    714 motd(char *fname)
    715 {
    716 	int fd, nchars;
    717 	sig_t oldint;
    718 	char tbuf[8192];
    719 
    720 	if ((fd = open(fname ? fname : _PATH_MOTDFILE, O_RDONLY, 0)) < 0)
    721 		return;
    722 	oldint = signal(SIGINT, sigint);
    723 	if (setjmp(motdinterrupt) == 0)
    724 		while ((nchars = read(fd, tbuf, sizeof(tbuf))) > 0)
    725 			(void)write(fileno(stdout), tbuf, nchars);
    726 	(void)signal(SIGINT, oldint);
    727 	(void)close(fd);
    728 }
    729 
    730 /* ARGSUSED */
    731 void
    732 sigint(int signo)
    733 {
    734 
    735 	longjmp(motdinterrupt, 1);
    736 }
    737 
    738 /* ARGSUSED */
    739 void
    740 timedout(int signo)
    741 {
    742 
    743 	(void)fprintf(stderr, "Login timed out after %d seconds\n", timeout);
    744 	exit(0);
    745 }
    746 
    747 static void
    748 update_db(int quietlog)
    749 {
    750 	if (nested != NULL) {
    751 		if (hostname != NULL)
    752 			syslog(LOG_NOTICE, "%s to %s on tty %s from %s",
    753 			    nested, pwd->pw_name, tty, hostname);
    754 		else
    755 			syslog(LOG_NOTICE, "%s to %s on tty %s", nested,
    756 			    pwd->pw_name, tty);
    757 
    758 	}
    759 	if (hostname != NULL && have_ss == 0) {
    760 		socklen_t len = sizeof(ss);
    761 		(void)getpeername(STDIN_FILENO, (struct sockaddr *)&ss, &len);
    762 	}
    763 	(void)gettimeofday(&now, NULL);
    764 }
    765 
    766 void
    767 badlogin(char *name)
    768 {
    769 
    770 	if (failures == 0)
    771 		return;
    772 	if (hostname) {
    773 		syslog(LOG_NOTICE, "%d LOGIN FAILURE%s FROM %s",
    774 		    failures, failures > 1 ? "S" : "", hostname);
    775 		syslog(LOG_AUTHPRIV|LOG_NOTICE,
    776 		    "%d LOGIN FAILURE%s FROM %s, %s",
    777 		    failures, failures > 1 ? "S" : "", hostname, name);
    778 	} else {
    779 		syslog(LOG_NOTICE, "%d LOGIN FAILURE%s ON %s",
    780 		    failures, failures > 1 ? "S" : "", tty);
    781 		syslog(LOG_AUTHPRIV|LOG_NOTICE,
    782 		    "%d LOGIN FAILURE%s ON %s, %s",
    783 		    failures, failures > 1 ? "S" : "", tty, name);
    784 	}
    785 }
    786 
    787 const char *
    788 stypeof(const char *ttyid)
    789 {
    790 	struct ttyent *t;
    791 
    792 	return (ttyid && (t = getttynam(ttyid)) ? t->ty_type : NULL);
    793 }
    794 
    795 void
    796 sleepexit(int eval)
    797 {
    798 
    799 	(void)sleep(5);
    800 	exit(eval);
    801 }
    802 
    803 void
    804 decode_ss(const char *arg)
    805 {
    806 	struct sockaddr_storage *ssp;
    807 	size_t len = strlen(arg);
    808 
    809 	if (len > sizeof(*ssp) * 4 + 1 || len < sizeof(*ssp))
    810 		errx(1, "Bad argument");
    811 
    812 	if ((ssp = malloc(len)) == NULL)
    813 		err(1, NULL);
    814 
    815 	if (strunvis((char *)ssp, arg) != sizeof(*ssp))
    816 		errx(1, "Decoding error");
    817 
    818 	(void)memcpy(&ss, ssp, sizeof(ss));
    819 	have_ss = 1;
    820 }
    821 
    822 void
    823 usage(void)
    824 {
    825 	(void)fprintf(stderr,
    826 	    "Usage: %s [-Ffps] [-a address] [-h hostname] [username]\n",
    827 	    getprogname());
    828 	exit(1);
    829 }
    830