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