Home | History | Annotate | Line # | Download | only in login
login_pam.c revision 1.17
      1 /*     $NetBSD: login_pam.c,v 1.17 2006/04/17 16:29:44 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.17 2006/04/17 16:29:44 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, pwres;
    110 char	pwbuf[1024];
    111 struct	group grs, *grp;
    112 char	grbuf[1024];
    113 int	failures, have_ss;
    114 char	term[64], *envinit[1], *hostname, *username, *tty, *nested;
    115 struct timeval now;
    116 struct sockaddr_storage ss;
    117 
    118 extern const char copyrightstr[];
    119 
    120 int
    121 main(int argc, char *argv[])
    122 {
    123 	extern char **environ;
    124 	struct stat st;
    125 	int ask, ch, cnt, fflag, pflag, quietlog, rootlogin;
    126 	int auth_passed;
    127 	uid_t uid, saved_uid;
    128 	gid_t saved_gid, saved_gids[NGROUPS_MAX];
    129 	int nsaved_gids;
    130 	char *domain, *p, *ttyn, *pwprompt;
    131 	char tbuf[MAXPATHLEN + 2], tname[sizeof(_PATH_TTY) + 10];
    132 	char localhost[MAXHOSTNAMELEN + 1];
    133 	int need_chpass, require_chpass;
    134 	int login_retries = DEFAULT_RETRIES,
    135 	    login_backoff = DEFAULT_BACKOFF;
    136 	char *shell = NULL;
    137 	login_cap_t *lc = NULL;
    138 	pam_handle_t *pamh = NULL;
    139 	int pam_err;
    140 	sig_t oint, oabrt, oquit, oalrm;
    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 	oabrt = signal(SIGABRT, SIG_IGN);
    154 	oalrm = signal(SIGALRM, timedout);
    155 	oint = signal(SIGINT, SIG_IGN);
    156 	oquit = signal(SIGQUIT, SIG_IGN);
    157 
    158 	(void)alarm(timeout);
    159 	(void)setpriority(PRIO_PROCESS, 0, 0);
    160 
    161 	openlog("login", 0, LOG_AUTH);
    162 
    163 	/*
    164 	 * -p is used by getty to tell login not to destroy the environment
    165 	 * -f is used to skip a second login authentication
    166 	 * -h is used by other servers to pass the name of the remote host to
    167 	 *    login so that it may be placed in utmp/utmpx and wtmp/wtmpx
    168 	 * -a in addition to -h, a server my supply -a to pass the actual
    169 	 *    server address.
    170 	 */
    171 	domain = NULL;
    172 	if (gethostname(localhost, sizeof(localhost)) < 0)
    173 		syslog(LOG_ERR, "couldn't get local hostname: %m");
    174 	else
    175 		domain = strchr(localhost, '.');
    176 	localhost[sizeof(localhost) - 1] = '\0';
    177 
    178 	fflag = pflag = 0;
    179 	have_ss = 0;
    180 	uid = getuid();
    181 	while ((ch = getopt(argc, argv, "a:fh:p")) != -1)
    182 		switch (ch) {
    183 		case 'a':
    184 			if (uid) {
    185 				errno = EPERM;
    186 				err(EXIT_FAILURE, "-a option");
    187 			}
    188 			decode_ss(optarg);
    189 #ifdef notdef
    190 			(void)sockaddr_snprintf(optarg,
    191 			    sizeof(struct sockaddr_storage), "%a", (void *)&ss);
    192 #endif
    193 			break;
    194 		case 'f':
    195 			fflag = 1;
    196 			break;
    197 		case 'h':
    198 			if (uid) {
    199 				errno = EPERM;
    200 				err(EXIT_FAILURE, "-h option");
    201 			}
    202 			if (domain && (p = strchr(optarg, '.')) != NULL &&
    203 			    strcasecmp(p, domain) == 0)
    204 				*p = '\0';
    205 			hostname = optarg;
    206 			break;
    207 		case 'p':
    208 			pflag = 1;
    209 			break;
    210 		default:
    211 		case '?':
    212 			usage();
    213 			break;
    214 		}
    215 
    216 	setproctitle(NULL);
    217 	argc -= optind;
    218 	argv += optind;
    219 
    220 	if (*argv) {
    221 		username = *argv;
    222 		ask = 0;
    223 	} else
    224 		ask = 1;
    225 
    226 #ifdef F_CLOSEM
    227 	(void)fcntl(3, F_CLOSEM, 0);
    228 #else
    229 	for (cnt = getdtablesize(); cnt > 2; cnt--)
    230 		(void)close(cnt);
    231 #endif
    232 
    233 	ttyn = ttyname(STDIN_FILENO);
    234 	if (ttyn == NULL || *ttyn == '\0') {
    235 		(void)snprintf(tname, sizeof(tname), "%s??", _PATH_TTY);
    236 		ttyn = tname;
    237 	}
    238 	if ((tty = strstr(ttyn, "/pts/")) != NULL)
    239 		++tty;
    240 	else if ((tty = strrchr(ttyn, '/')) != NULL)
    241 		++tty;
    242 	else
    243 		tty = ttyn;
    244 
    245 	if (issetugid()) {
    246 		nested = strdup(user_from_uid(getuid(), 0));
    247 		if (nested == NULL) {
    248                 	syslog(LOG_ERR, "strdup: %m");
    249                 	sleepexit(EXIT_FAILURE);
    250 		}
    251 	}
    252 
    253 	/* Get "login-retries" and "login-backoff" from default class */
    254 	if ((lc = login_getclass(NULL)) != NULL) {
    255 		login_retries = (int)login_getcapnum(lc, "login-retries",
    256 		    DEFAULT_RETRIES, DEFAULT_RETRIES);
    257 		login_backoff = (int)login_getcapnum(lc, "login-backoff",
    258 		    DEFAULT_BACKOFF, DEFAULT_BACKOFF);
    259 		login_close(lc);
    260 		lc = NULL;
    261 	}
    262 
    263 
    264 	for (cnt = 0;; ask = 1) {
    265 		if (ask) {
    266 			fflag = 0;
    267 			getloginname();
    268 		}
    269 		rootlogin = 0;
    270 		auth_passed = 0;
    271 		if (strlen(username) > MAXLOGNAME)
    272 			username[MAXLOGNAME] = '\0';
    273 
    274 		/*
    275 		 * Note if trying multiple user names; log failures for
    276 		 * previous user name, but don't bother logging one failure
    277 		 * for nonexistent name (mistyped username).
    278 		 */
    279 		if (failures && strcmp(tbuf, username)) {
    280 			if (failures > (pwd ? 0 : 1))
    281 				badlogin(tbuf);
    282 			failures = 0;
    283 		}
    284 
    285 #define PAM_END(msg) do { 						\
    286 	syslog(LOG_ERR, "%s: %s", msg, pam_strerror(pamh, pam_err)); 	\
    287 	warnx("%s: %s", msg, pam_strerror(pamh, pam_err));		\
    288 	pam_end(pamh, pam_err);						\
    289 	sleepexit(EXIT_FAILURE);					\
    290 } while (/*CONSTCOND*/0)
    291 
    292 		pam_err = pam_start("login", username, &pamc, &pamh);
    293 		if (pam_err != PAM_SUCCESS) {
    294 			if (pamh != NULL)
    295 				PAM_END("pam_start");
    296 			/* Things went really bad... */
    297 			syslog(LOG_ERR, "pam_start failed: %s",
    298 			    pam_strerror(pamh, pam_err));
    299 			errx(EXIT_FAILURE, "pam_start failed");
    300 		}
    301 
    302 #define PAM_SET_ITEM(item, var)	do {					\
    303 	pam_err = pam_set_item(pamh, (item), (var));			\
    304 	if (pam_err != PAM_SUCCESS)					\
    305 		PAM_END("pam_set_item(" # item ")");			\
    306 } while (/*CONSTCOND*/0)
    307 
    308 		/*
    309 		 * Fill hostname tty, and nested user
    310 		 */
    311 		PAM_SET_ITEM(PAM_RHOST, hostname);
    312 		PAM_SET_ITEM(PAM_TTY, tty);
    313 		if (nested)
    314 			PAM_SET_ITEM(PAM_NUSER, nested);
    315 		if (have_ss)
    316 			PAM_SET_ITEM(PAM_SOCKADDR, &ss);
    317 
    318 		/*
    319 		 * Don't check for errors, because we don't want to give
    320 		 * out any information.
    321 		 */
    322 		pwd = NULL;
    323 		(void)getpwnam_r(username, &pwres, pwbuf, sizeof(pwbuf), &pwd);
    324 
    325 		/*
    326 		 * Establish the class now, before we might goto
    327 		 * within the next block. pwd can be NULL since it
    328 		 * falls back to the "default" class if it is.
    329 		 */
    330 		lc = login_getclass(pwd ? pwd->pw_class : NULL);
    331 
    332 		/*
    333 		 * if we have a valid account name, and it doesn't have a
    334 		 * password, or the -f option was specified and the caller
    335 		 * is root or the caller isn't changing their uid, don't
    336 		 * authenticate.
    337 		 */
    338 		if (pwd) {
    339 			if (pwd->pw_uid == 0)
    340 				rootlogin = 1;
    341 
    342 			if (fflag && (uid == 0 || uid == pwd->pw_uid)) {
    343 				/* already authenticated */
    344 				auth_passed = 1;
    345 				goto skip_auth;
    346 			}
    347 		}
    348 
    349 		(void)setpriority(PRIO_PROCESS, 0, -4);
    350 
    351 		switch(pam_err = pam_authenticate(pamh, pam_silent)) {
    352 		case PAM_SUCCESS:
    353 			/*
    354 			 * PAM can change the user, refresh
    355 			 * username, pwd, and lc.
    356 			 */
    357 			pam_err = pam_get_item(pamh, PAM_USER, &newuser);
    358 			if (pam_err != PAM_SUCCESS)
    359 				PAM_END("pam_get_item(PAM_USER)");
    360 
    361 			username = (char *)newuser;
    362 			/*
    363 			 * Don't check for errors, because we don't want to give
    364 			 * out any information.
    365 			 */
    366 			pwd = NULL;
    367 			(void)getpwnam_r(username, &pwres, pwbuf, sizeof(pwbuf),
    368 			    &pwd);
    369 			lc = login_getpwclass(pwd);
    370 			auth_passed = 1;
    371 
    372 			switch (pam_err = pam_acct_mgmt(pamh, pam_silent)) {
    373 			case PAM_SUCCESS:
    374 				break;
    375 
    376 			case PAM_NEW_AUTHTOK_REQD:
    377 				pam_err = pam_chauthtok(pamh,
    378 				    pam_silent|PAM_CHANGE_EXPIRED_AUTHTOK);
    379 
    380 				if (pam_err != PAM_SUCCESS)
    381 					PAM_END("pam_chauthtok");
    382 				break;
    383 
    384 			case PAM_AUTH_ERR:
    385 			case PAM_USER_UNKNOWN:
    386 			case PAM_MAXTRIES:
    387 				auth_passed = 0;
    388 				break;
    389 
    390 			default:
    391 				PAM_END("pam_acct_mgmt");
    392 				break;
    393 			}
    394 			break;
    395 
    396 		case PAM_AUTH_ERR:
    397 		case PAM_USER_UNKNOWN:
    398 		case PAM_MAXTRIES:
    399 			auth_passed = 0;
    400 			break;
    401 
    402 		default:
    403 			PAM_END("pam_authenticate");
    404 			break;
    405 		}
    406 
    407 		(void)setpriority(PRIO_PROCESS, 0, 0);
    408 
    409 skip_auth:
    410 		/*
    411 		 * If the user exists and authentication passed,
    412 		 * get out of the loop and login the user.
    413 		 */
    414 		if (pwd && auth_passed)
    415 			break;
    416 
    417 		(void)printf("Login incorrect or refused on this terminal.\n");
    418 		failures++;
    419 		cnt++;
    420 		/*
    421 		 * We allow login_retries tries, but after login_backoff
    422 		 * we start backing off.  These default to 10 and 3
    423 		 * respectively.
    424 		 */
    425 		if (cnt > login_backoff) {
    426 			if (cnt >= login_retries) {
    427 				badlogin(username);
    428 				pam_end(pamh, PAM_SUCCESS);
    429 				sleepexit(EXIT_FAILURE);
    430 			}
    431 			sleep((u_int)((cnt - login_backoff) * 5));
    432 		}
    433 	}
    434 
    435 	/* committed to login -- turn off timeout */
    436 	(void)alarm((u_int)0);
    437 
    438 	endpwent();
    439 
    440         quietlog = login_getcapbool(lc, "hushlogin", 0);
    441 
    442 	/*
    443 	 * Temporarily give up special privileges so we can change
    444 	 * into NFS-mounted homes that are exported for non-root
    445 	 * access and have mode 7x0
    446 	 */
    447 	saved_uid = geteuid();
    448 	saved_gid = getegid();
    449 	nsaved_gids = getgroups(NGROUPS_MAX, saved_gids);
    450 
    451 	(void)setegid(pwd->pw_gid);
    452 	initgroups(username, pwd->pw_gid);
    453 	(void)seteuid(pwd->pw_uid);
    454 
    455 	if (chdir(pwd->pw_dir) != 0) {
    456                 if (login_getcapbool(lc, "requirehome", 0)) {
    457 			(void)printf("Home directory %s required\n",
    458 			    pwd->pw_dir);
    459 			pam_end(pamh, PAM_SUCCESS);
    460                         exit(EXIT_FAILURE);
    461 		}
    462 
    463 		(void)printf("No home directory %s!\n", pwd->pw_dir);
    464 		if (chdir("/")) {
    465 			pam_end(pamh, PAM_SUCCESS);
    466 			exit(EXIT_SUCCESS);
    467 		}
    468 		pwd->pw_dir = "/";
    469 		(void)printf("Logging in with home = \"/\".\n");
    470 	}
    471 
    472 	if (!quietlog) {
    473 		quietlog = access(_PATH_HUSHLOGIN, F_OK) == 0;
    474 		pam_silent = quietlog ? PAM_SILENT : 0;
    475 	}
    476 
    477 	/* regain special privileges */
    478 	setegid(saved_gid);
    479 	setgroups(nsaved_gids, saved_gids);
    480 	seteuid(saved_uid);
    481 
    482 	(void)getgrnam_r(TTYGRPNAME, &grs, grbuf, sizeof(grbuf), &grp);
    483 	(void)chown(ttyn, pwd->pw_uid,
    484 	    (grp != NULL) ? grp->gr_gid : pwd->pw_gid);
    485 
    486 	if (ttyaction(ttyn, "login", pwd->pw_name))
    487 		(void)printf("Warning: ttyaction failed.\n");
    488 
    489 	/* Nothing else left to fail -- really log in. */
    490         update_db(quietlog);
    491 
    492 	if (nested == NULL && setusercontext(lc, pwd, pwd->pw_uid,
    493 	    LOGIN_SETLOGIN) != 0) {
    494 		syslog(LOG_ERR, "setusercontext failed");
    495 		pam_end(pamh, PAM_SUCCESS);
    496 		exit(EXIT_FAILURE);
    497 	}
    498 
    499 	if (tty[sizeof("tty")-1] == 'd')
    500 		syslog(LOG_INFO, "DIALUP %s, %s", tty, pwd->pw_name);
    501 
    502 	/* If fflag is on, assume caller/authenticator has logged root login. */
    503 	if (rootlogin && fflag == 0) {
    504 		if (hostname)
    505 			syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s FROM %s",
    506 			    username, tty, hostname);
    507 		else
    508 			syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s",
    509 			    username, tty);
    510 	}
    511 
    512 	/*
    513 	 * Establish groups
    514 	 */
    515 	if (setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETGROUP) != 0) {
    516 		syslog(LOG_ERR, "setusercontext failed");
    517 		pam_end(pamh, PAM_SUCCESS);
    518 		exit(EXIT_FAILURE);
    519 	}
    520 
    521 	pam_err = pam_setcred(pamh, pam_silent|PAM_ESTABLISH_CRED);
    522 	if (pam_err != PAM_SUCCESS)
    523 		PAM_END("pam_setcred");
    524 
    525 	pam_err = pam_open_session(pamh, pam_silent);
    526 	if (pam_err != PAM_SUCCESS)
    527 		PAM_END("pam_open_session");
    528 
    529 	/*
    530 	 * Fork because we need to call pam_closesession as root.
    531 	 * Make sure signals cannot kill the parent.
    532 	 * This has been handled in the begining of main.
    533 	 */
    534 
    535 	switch(pid = fork()) {
    536 	case -1:
    537 		pam_err = pam_close_session(pamh, 0);
    538 		if (pam_err != PAM_SUCCESS) {
    539 			syslog(LOG_ERR, "pam_close_session: %s",
    540 			    pam_strerror(pamh, pam_err));
    541 			warnx("pam_close_session: %s",
    542 			    pam_strerror(pamh, pam_err));
    543 		}
    544 		syslog(LOG_ERR, "fork failed: %m");
    545 		warn("fork failed");
    546 		pam_end(pamh, pam_err);
    547 		exit(EXIT_FAILURE);
    548 		break;
    549 
    550 	case 0: /* Child */
    551 		break;
    552 
    553 	default:
    554 		/*
    555 		 * Parent: wait for the child to terminate
    556 		 * and call pam_close_session.
    557 		 */
    558 		if ((xpid = waitpid(pid, &status, 0)) != pid) {
    559 			pam_err = pam_close_session(pamh, 0);
    560 			if (pam_err != PAM_SUCCESS) {
    561 				syslog(LOG_ERR,
    562 				    "pam_close_session: %s",
    563 				    pam_strerror(pamh, pam_err));
    564 				warnx("pam_close_session: %s",
    565 				    pam_strerror(pamh, pam_err));
    566 			}
    567 			pam_end(pamh, pam_err);
    568 			if (xpid != -1)
    569 				warnx("wrong PID: %d != %d", pid, xpid);
    570 			else
    571 				warn("wait for pid %d failed", pid);
    572 			exit(EXIT_FAILURE);
    573 		}
    574 
    575 		(void)signal(SIGABRT, oabrt);
    576 		(void)signal(SIGALRM, oalrm);
    577 		(void)signal(SIGINT, oint);
    578 		(void)signal(SIGQUIT, oquit);
    579 		if ((pam_err = pam_close_session(pamh, 0)) != PAM_SUCCESS) {
    580 			syslog(LOG_ERR, "pam_close_session: %s",
    581 			    pam_strerror(pamh, pam_err));
    582 			warnx("pam_close_session: %s",
    583 			    pam_strerror(pamh, pam_err));
    584 		}
    585 		pam_end(pamh, PAM_SUCCESS);
    586 		exit(EXIT_SUCCESS);
    587 		break;
    588 	}
    589 
    590 	/*
    591 	 * The child: starting here, we don't have to care about
    592 	 * handling PAM issues if we exit, the parent will do the
    593 	 * job when we exit.
    594          *
    595 	 * Destroy environment unless user has requested its preservation.
    596 	 * Try to preserve TERM anyway.
    597 	 */
    598 	saved_term = getenv("TERM");
    599 	if (!pflag) {
    600 		environ = envinit;
    601 		if (saved_term)
    602 			setenv("TERM", saved_term, 0);
    603 	}
    604 
    605 	if (*pwd->pw_shell == '\0')
    606 		pwd->pw_shell = _PATH_BSHELL;
    607 
    608 	shell = login_getcapstr(lc, "shell", pwd->pw_shell, pwd->pw_shell);
    609 	if (*shell == '\0')
    610 		shell = pwd->pw_shell;
    611 
    612 	if ((pwd->pw_shell = strdup(shell)) == NULL) {
    613 		syslog(LOG_ERR, "Cannot alloc mem");
    614 		exit(EXIT_FAILURE);
    615 	}
    616 
    617 	(void)setenv("HOME", pwd->pw_dir, 1);
    618 	(void)setenv("SHELL", pwd->pw_shell, 1);
    619 	if (term[0] == '\0') {
    620 		char *tt = (char *)stypeof(tty);
    621 
    622 		if (tt == NULL)
    623 			tt = login_getcapstr(lc, "term", NULL, NULL);
    624 
    625 		/* unknown term -> "su" */
    626 		(void)strlcpy(term, tt != NULL ? tt : "su", sizeof(term));
    627 	}
    628 	(void)setenv("TERM", term, 0);
    629 	(void)setenv("LOGNAME", pwd->pw_name, 1);
    630 	(void)setenv("USER", pwd->pw_name, 1);
    631 
    632 	/*
    633 	 * Add PAM environement
    634 	 */
    635 	if ((pamenv = pam_getenvlist(pamh)) != NULL) {
    636 		char **envitem;
    637 
    638 		for (envitem = pamenv; *envitem; envitem++) {
    639 			putenv(*envitem);
    640 			free(*envitem);
    641 		}
    642 
    643 		free(pamenv);
    644 	}
    645 
    646 	/* This drops root privs */
    647 	if (setusercontext(lc, pwd, pwd->pw_uid,
    648 	    (LOGIN_SETALL & ~LOGIN_SETLOGIN)) != 0) {
    649 		syslog(LOG_ERR, "setusercontext failed");
    650 		exit(EXIT_FAILURE);
    651 	}
    652 
    653 	if (!quietlog) {
    654 		char *fname;
    655 
    656 		fname = login_getcapstr(lc, "copyright", NULL, NULL);
    657 		if (fname != NULL && access(fname, F_OK) == 0)
    658 			motd(fname);
    659 		else
    660 			(void)printf("%s", copyrightstr);
    661 
    662                 fname = login_getcapstr(lc, "welcome", NULL, NULL);
    663                 if (fname == NULL || access(fname, F_OK) != 0)
    664                         fname = _PATH_MOTDFILE;
    665                 motd(fname);
    666 
    667 		(void)snprintf(tbuf,
    668 		    sizeof(tbuf), "%s/%s", _PATH_MAILDIR, pwd->pw_name);
    669 		if (stat(tbuf, &st) == 0 && st.st_size != 0)
    670 			(void)printf("You have %smail.\n",
    671 			    (st.st_mtime > st.st_atime) ? "new " : "");
    672 	}
    673 
    674 	login_close(lc);
    675 
    676 
    677 	tbuf[0] = '-';
    678 	(void)strlcpy(tbuf + 1, (p = strrchr(pwd->pw_shell, '/')) ?
    679 	    p + 1 : pwd->pw_shell, sizeof(tbuf) - 1);
    680 
    681 	(void)signal(SIGABRT, oabrt);
    682 	(void)signal(SIGALRM, oalrm);
    683 	(void)signal(SIGINT, oint);
    684 	(void)signal(SIGQUIT, oquit);
    685 	(void)signal(SIGTSTP, SIG_IGN);
    686 
    687 	execlp(pwd->pw_shell, tbuf, NULL);
    688 	err(EXIT_FAILURE, "%s", pwd->pw_shell);
    689 }
    690 
    691 #define	NBUFSIZ		(MAXLOGNAME + 1)
    692 
    693 
    694 void
    695 getloginname(void)
    696 {
    697 	int ch;
    698 	char *p;
    699 	static char nbuf[NBUFSIZ];
    700 
    701 	for (;;) {
    702 		(void)printf("login: ");
    703 		for (p = nbuf; (ch = getchar()) != '\n'; ) {
    704 			if (ch == EOF) {
    705 				badlogin(username);
    706 				exit(EXIT_SUCCESS);
    707 			}
    708 			if (p < nbuf + (NBUFSIZ - 1))
    709 				*p++ = ch;
    710 		}
    711 		if (p > nbuf) {
    712 			if (nbuf[0] == '-')
    713 				(void)fprintf(stderr,
    714 				    "login names may not start with '-'.\n");
    715 			else {
    716 				*p = '\0';
    717 				username = nbuf;
    718 				break;
    719 			}
    720 		}
    721 	}
    722 }
    723 
    724 int
    725 rootterm(char *ttyn)
    726 {
    727 	struct ttyent *t;
    728 
    729 	return ((t = getttynam(ttyn)) && t->ty_status & TTY_SECURE);
    730 }
    731 
    732 jmp_buf motdinterrupt;
    733 
    734 void
    735 motd(char *fname)
    736 {
    737 	int fd, nchars;
    738 	sig_t oldint;
    739 	char tbuf[8192];
    740 
    741 	if ((fd = open(fname ? fname : _PATH_MOTDFILE, O_RDONLY, 0)) < 0)
    742 		return;
    743 	oldint = signal(SIGINT, sigint);
    744 	if (setjmp(motdinterrupt) == 0)
    745 		while ((nchars = read(fd, tbuf, sizeof(tbuf))) > 0)
    746 			(void)write(fileno(stdout), tbuf, nchars);
    747 	(void)signal(SIGINT, oldint);
    748 	(void)close(fd);
    749 }
    750 
    751 /* ARGSUSED */
    752 void
    753 sigint(int signo)
    754 {
    755 
    756 	longjmp(motdinterrupt, 1);
    757 }
    758 
    759 /* ARGSUSED */
    760 void
    761 timedout(int signo)
    762 {
    763 
    764 	(void)fprintf(stderr, "Login timed out after %d seconds\n", timeout);
    765 	exit(EXIT_SUCCESS);
    766 }
    767 
    768 static void
    769 update_db(int quietlog)
    770 {
    771 	if (nested != NULL) {
    772 		if (hostname != NULL)
    773 			syslog(LOG_NOTICE, "%s to %s on tty %s from %s",
    774 			    nested, pwd->pw_name, tty, hostname);
    775 		else
    776 			syslog(LOG_NOTICE, "%s to %s on tty %s", nested,
    777 			    pwd->pw_name, tty);
    778 
    779 	}
    780 	if (hostname != NULL && have_ss == 0) {
    781 		socklen_t len = sizeof(ss);
    782 		have_ss = getpeername(STDIN_FILENO, (struct sockaddr *)&ss,
    783 		    &len) != -1;
    784 	}
    785 	(void)gettimeofday(&now, NULL);
    786 }
    787 
    788 void
    789 badlogin(char *name)
    790 {
    791 
    792 	if (failures == 0)
    793 		return;
    794 	if (hostname) {
    795 		syslog(LOG_NOTICE, "%d LOGIN FAILURE%s FROM %s",
    796 		    failures, failures > 1 ? "S" : "", hostname);
    797 		syslog(LOG_AUTHPRIV|LOG_NOTICE,
    798 		    "%d LOGIN FAILURE%s FROM %s, %s",
    799 		    failures, failures > 1 ? "S" : "", hostname, name);
    800 	} else {
    801 		syslog(LOG_NOTICE, "%d LOGIN FAILURE%s ON %s",
    802 		    failures, failures > 1 ? "S" : "", tty);
    803 		syslog(LOG_AUTHPRIV|LOG_NOTICE,
    804 		    "%d LOGIN FAILURE%s ON %s, %s",
    805 		    failures, failures > 1 ? "S" : "", tty, name);
    806 	}
    807 }
    808 
    809 const char *
    810 stypeof(const char *ttyid)
    811 {
    812 	struct ttyent *t;
    813 
    814 	return (ttyid && (t = getttynam(ttyid)) ? t->ty_type : NULL);
    815 }
    816 
    817 void
    818 sleepexit(int eval)
    819 {
    820 
    821 	(void)sleep(5);
    822 	exit(eval);
    823 }
    824 
    825 void
    826 decode_ss(const char *arg)
    827 {
    828 	struct sockaddr_storage *ssp;
    829 	size_t len = strlen(arg);
    830 
    831 	if (len > sizeof(*ssp) * 4 + 1 || len < sizeof(*ssp))
    832 		errx(EXIT_FAILURE, "Bad argument");
    833 
    834 	if ((ssp = malloc(len)) == NULL)
    835 		err(EXIT_FAILURE, NULL);
    836 
    837 	if (strunvis((char *)ssp, arg) != sizeof(*ssp))
    838 		errx(EXIT_FAILURE, "Decoding error");
    839 
    840 	(void)memcpy(&ss, ssp, sizeof(ss));
    841 	have_ss = 1;
    842 	free(ssp);
    843 }
    844 
    845 void
    846 usage(void)
    847 {
    848 	(void)fprintf(stderr,
    849 	    "Usage: %s [-fp] [-a address] [-h hostname] [username]\n",
    850 	    getprogname());
    851 	exit(EXIT_FAILURE);
    852 }
    853