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