Home | History | Annotate | Line # | Download | only in login
login.c revision 1.77
      1 /*     $NetBSD: login.c,v 1.77 2004/01/05 03:53:10 lukem 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.c,v 1.77 2004/01/05 03:53:10 lukem 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 #ifdef SUPPORT_UTMP
     75 #include <utmp.h>
     76 #endif
     77 #ifdef SUPPORT_UTMPX
     78 #include <utmpx.h>
     79 #endif
     80 #include <util.h>
     81 #ifdef SKEY
     82 #include <skey.h>
     83 #endif
     84 #ifdef KERBEROS5
     85 #include <krb5/krb5.h>
     86 #include <com_err.h>
     87 #endif
     88 #ifdef LOGIN_CAP
     89 #include <login_cap.h>
     90 #endif
     91 
     92 #include "pathnames.h"
     93 
     94 #ifdef KERBEROS5
     95 int login_krb5_get_tickets = 1;
     96 int login_krb4_get_tickets = 0;
     97 int login_krb5_forwardable_tgt = 0;
     98 int login_krb5_retain_ccache = 0;
     99 #endif
    100 
    101 void	 badlogin __P((char *));
    102 void	 checknologin __P((char *));
    103 #ifdef SUPPORT_UTMP
    104 static void	 doutmp __P((void));
    105 static void	 dolastlog __P((int));
    106 #endif
    107 #ifdef SUPPORT_UTMPX
    108 static void	 doutmpx __P((void));
    109 static void	 dolastlogx __P((int));
    110 #endif
    111 static void	 update_db __P((int));
    112 void	 getloginname __P((void));
    113 int	 main __P((int, char *[]));
    114 void	 motd __P((char *));
    115 int	 rootterm __P((char *));
    116 void	 sigint __P((int));
    117 void	 sleepexit __P((int));
    118 const	 char *stypeof __P((const char *));
    119 void	 timedout __P((int));
    120 #if defined(KERBEROS)
    121 int	 klogin __P((struct passwd *, char *, char *, char *));
    122 void	 kdestroy __P((void));
    123 #endif
    124 #ifdef KERBEROS5
    125 int	 k5login __P((struct passwd *, char *, char *, char *));
    126 void	 k5destroy __P((void));
    127 int	 k5_read_creds __P((char*));
    128 int	 k5_write_creds __P((void));
    129 #endif
    130 #if defined(KERBEROS) || defined(KERBEROS5)
    131 void	 dofork __P((void));
    132 #endif
    133 
    134 #define	TTYGRPNAME	"tty"		/* name of group to own ttys */
    135 
    136 #define DEFAULT_BACKOFF 3
    137 #define DEFAULT_RETRIES 10
    138 
    139 /*
    140  * This bounds the time given to login.  Not a define so it can
    141  * be patched on machines where it's too small.
    142  */
    143 u_int	timeout = 300;
    144 
    145 #if defined(KERBEROS) || defined(KERBEROS5)
    146 int	notickets = 1;
    147 char	*instance;
    148 int	has_ccache = 0;
    149 #endif
    150 #ifdef KERBEROS
    151 extern char	*krbtkfile_env;
    152 extern int	krb_configured;
    153 #endif
    154 #ifdef KERBEROS5
    155 extern krb5_context kcontext;
    156 extern int	have_forward;
    157 extern char	*krb5tkfile_env;
    158 extern int	krb5_configured;
    159 #endif
    160 
    161 #if defined(KERBEROS) && defined(KERBEROS5)
    162 #define	KERBEROS_CONFIGURED	(krb_configured || krb5_configured)
    163 #elif defined(KERBEROS)
    164 #define	KERBEROS_CONFIGURED	krb_configured
    165 #elif defined(KERBEROS5)
    166 #define	KERBEROS_CONFIGURED	krb5_configured
    167 #endif
    168 
    169 struct	passwd *pwd;
    170 int	failures;
    171 char	term[64], *envinit[1], *hostname, *username, *tty, *nested;
    172 struct timeval now;
    173 struct sockaddr_storage ss;
    174 
    175 extern const char copyrightstr[];
    176 
    177 int
    178 main(argc, argv)
    179 	int argc;
    180 	char *argv[];
    181 {
    182 	extern char **environ;
    183 	struct group *gr;
    184 	struct stat st;
    185 	int ask, ch, cnt, fflag, hflag, pflag, sflag, quietlog, rootlogin, rval;
    186 	int Fflag;
    187 	uid_t uid, saved_uid;
    188 	gid_t saved_gid, saved_gids[NGROUPS_MAX];
    189 	int nsaved_gids;
    190 	char *domain, *p, *ttyn, *pwprompt;
    191 	const char *salt;
    192 	char tbuf[MAXPATHLEN + 2], tname[sizeof(_PATH_TTY) + 10];
    193 	char localhost[MAXHOSTNAMELEN + 1];
    194 	int need_chpass, require_chpass;
    195 	int login_retries = DEFAULT_RETRIES,
    196 	    login_backoff = DEFAULT_BACKOFF;
    197 	time_t pw_warntime = _PASSWORD_WARNDAYS * SECSPERDAY;
    198 #ifdef KERBEROS5
    199 	krb5_error_code kerror;
    200 #endif
    201 #if defined(KERBEROS) || defined(KERBEROS5)
    202 	int got_tickets = 0;
    203 #endif
    204 #ifdef LOGIN_CAP
    205 	char *shell = NULL;
    206 	login_cap_t *lc = NULL;
    207 #endif
    208 
    209 	tbuf[0] = '\0';
    210 	rval = 0;
    211 	pwprompt = NULL;
    212 	nested = NULL;
    213 	need_chpass = require_chpass = 0;
    214 
    215 	(void)signal(SIGALRM, timedout);
    216 	(void)alarm(timeout);
    217 	(void)signal(SIGQUIT, SIG_IGN);
    218 	(void)signal(SIGINT, SIG_IGN);
    219 	(void)setpriority(PRIO_PROCESS, 0, 0);
    220 
    221 	openlog("login", 0, LOG_AUTH);
    222 
    223 	/*
    224 	 * -p is used by getty to tell login not to destroy the environment
    225 	 * -f is used to skip a second login authentication
    226 	 * -h is used by other servers to pass the name of the remote host to
    227 	 *    login so that it may be placed in utmp/utmpx and wtmp/wtmpx
    228 	 * -s is used to force use of S/Key or equivalent.
    229 	 */
    230 	domain = NULL;
    231 	if (gethostname(localhost, sizeof(localhost)) < 0)
    232 		syslog(LOG_ERR, "couldn't get local hostname: %m");
    233 	else
    234 		domain = strchr(localhost, '.');
    235 	localhost[sizeof(localhost) - 1] = '\0';
    236 
    237 	Fflag = fflag = hflag = pflag = sflag = 0;
    238 #ifdef KERBEROS5
    239 	have_forward = 0;
    240 #endif
    241 	uid = getuid();
    242 	while ((ch = getopt(argc, argv, "Ffh:ps")) != -1)
    243 		switch (ch) {
    244 		case 'F':
    245 			Fflag = 1;
    246 			/* FALLTHROUGH */
    247 		case 'f':
    248 			fflag = 1;
    249 			break;
    250 		case 'h':
    251 			if (uid)
    252 				errx(1, "-h option: %s", strerror(EPERM));
    253 			hflag = 1;
    254 			if (domain && (p = strchr(optarg, '.')) != NULL &&
    255 			    strcasecmp(p, domain) == 0)
    256 				*p = 0;
    257 			hostname = optarg;
    258 			break;
    259 		case 'p':
    260 			pflag = 1;
    261 			break;
    262 		case 's':
    263 			sflag = 1;
    264 			break;
    265 		default:
    266 		case '?':
    267 			(void)fprintf(stderr,
    268 			    "usage: login [-fps] [-h hostname] [username]\n");
    269 			exit(1);
    270 		}
    271 	argc -= optind;
    272 	argv += optind;
    273 
    274 	if (*argv) {
    275 		username = *argv;
    276 		ask = 0;
    277 	} else
    278 		ask = 1;
    279 
    280 	for (cnt = getdtablesize(); cnt > 2; cnt--)
    281 		(void)close(cnt);
    282 
    283 	ttyn = ttyname(STDIN_FILENO);
    284 	if (ttyn == NULL || *ttyn == '\0') {
    285 		(void)snprintf(tname, sizeof(tname), "%s??", _PATH_TTY);
    286 		ttyn = tname;
    287 	}
    288 	if ((tty = strrchr(ttyn, '/')) != NULL)
    289 		++tty;
    290 	else
    291 		tty = ttyn;
    292 
    293 	if (issetugid()) {
    294 		nested = strdup(user_from_uid(getuid(), 0));
    295 		if (nested == NULL) {
    296                 	syslog(LOG_ERR, "strdup: %m");
    297                 	sleepexit(1);
    298 		}
    299 	}
    300 
    301 #ifdef LOGIN_CAP
    302 	/* Get "login-retries" and "login-backoff" from default class */
    303 	if ((lc = login_getclass(NULL)) != NULL) {
    304 		login_retries = (int)login_getcapnum(lc, "login-retries",
    305 		    DEFAULT_RETRIES, DEFAULT_RETRIES);
    306 		login_backoff = (int)login_getcapnum(lc, "login-backoff",
    307 		    DEFAULT_BACKOFF, DEFAULT_BACKOFF);
    308 		login_close(lc);
    309 		lc = NULL;
    310 	}
    311 #endif
    312 
    313 #ifdef KERBEROS5
    314 	kerror = krb5_init_context(&kcontext);
    315 	if (kerror) {
    316 		/*
    317 		 * If Kerberos is not configured, that is, we are
    318 		 * not using Kerberos, do not log the error message.
    319 		 * However, if Kerberos is configured,  and the
    320 		 * context init fails for some other reason, we need
    321 		 * to issue a no tickets warning to the user when the
    322 		 * login succeeds.
    323 		 */
    324 		if (kerror != ENXIO) {	/* XXX NetBSD-local Heimdal hack */
    325 			syslog(LOG_NOTICE,
    326 			    "%s when initializing Kerberos context",
    327 			    error_message(kerror));
    328 			krb5_configured = 1;
    329 		}
    330 		login_krb5_get_tickets = 0;
    331 	}
    332 #endif /* KERBEROS5 */
    333 
    334 	for (cnt = 0;; ask = 1) {
    335 #if defined(KERBEROS)
    336 	        kdestroy();
    337 #endif
    338 #if defined(KERBEROS5)
    339 		if (login_krb5_get_tickets)
    340 			k5destroy();
    341 #endif
    342 		if (ask) {
    343 			fflag = 0;
    344 			getloginname();
    345 		}
    346 		rootlogin = 0;
    347 #ifdef KERBEROS
    348 		if ((instance = strchr(username, '.')) != NULL)
    349 			*instance++ = '\0';
    350 		else
    351 			instance = "";
    352 #endif
    353 #ifdef KERBEROS5
    354 		if ((instance = strchr(username, '/')) != NULL)
    355 			*instance++ = '\0';
    356 		else
    357 			instance = "";
    358 #endif
    359 		if (strlen(username) > MAXLOGNAME)
    360 			username[MAXLOGNAME] = '\0';
    361 
    362 		/*
    363 		 * Note if trying multiple user names; log failures for
    364 		 * previous user name, but don't bother logging one failure
    365 		 * for nonexistent name (mistyped username).
    366 		 */
    367 		if (failures && strcmp(tbuf, username)) {
    368 			if (failures > (pwd ? 0 : 1))
    369 				badlogin(tbuf);
    370 			failures = 0;
    371 		}
    372 		(void)strlcpy(tbuf, username, sizeof(tbuf));
    373 
    374 		if ((pwd = getpwnam(username)) != NULL)
    375 			salt = pwd->pw_passwd;
    376 		else
    377 			salt = "xx";
    378 
    379 #ifdef LOGIN_CAP
    380 		/*
    381 		 * Establish the class now, before we might goto
    382 		 * within the next block. pwd can be NULL since it
    383 		 * falls back to the "default" class if it is.
    384 		 */
    385 		lc = login_getclass(pwd ? pwd->pw_class : NULL);
    386 #endif
    387 		/*
    388 		 * if we have a valid account name, and it doesn't have a
    389 		 * password, or the -f option was specified and the caller
    390 		 * is root or the caller isn't changing their uid, don't
    391 		 * authenticate.
    392 		 */
    393 		if (pwd) {
    394 			if (pwd->pw_uid == 0)
    395 				rootlogin = 1;
    396 
    397 			if (fflag && (uid == 0 || uid == pwd->pw_uid)) {
    398 				/* already authenticated */
    399 #ifdef KERBEROS5
    400 				if (login_krb5_get_tickets && Fflag)
    401 					k5_read_creds(username);
    402 #endif
    403 				break;
    404 			} else if (pwd->pw_passwd[0] == '\0') {
    405 				/* pretend password okay */
    406 				rval = 0;
    407 				goto ttycheck;
    408 			}
    409 		}
    410 
    411 		fflag = 0;
    412 
    413 		(void)setpriority(PRIO_PROCESS, 0, -4);
    414 
    415 #ifdef SKEY
    416 		if (skey_haskey(username) == 0) {
    417 			static char skprompt[80];
    418 			const char *skinfo = skey_keyinfo(username);
    419 
    420 			(void)snprintf(skprompt, sizeof(skprompt),
    421 			    "Password [%s]:",
    422 			    skinfo ? skinfo : "error getting challenge");
    423 			pwprompt = skprompt;
    424 		} else
    425 #endif
    426 			pwprompt = "Password:";
    427 
    428 		p = getpass(pwprompt);
    429 
    430 		if (pwd == NULL) {
    431 			rval = 1;
    432 			goto skip;
    433 		}
    434 #ifdef KERBEROS
    435 		if (
    436 #ifdef KERBEROS5
    437 		    /* allow a user to get both krb4 and krb5 tickets, if
    438 		     * desired.  If krb5 is compiled in, the default action
    439 		     * is to ignore krb4 and get krb5 tickets, but the user
    440 		     * can override this in the krb5.conf. */
    441 		    login_krb4_get_tickets &&
    442 #endif
    443 		    klogin(pwd, instance, localhost, p) == 0) {
    444 			rval = 0;
    445 			got_tickets = 1;
    446 		}
    447 #endif
    448 #ifdef KERBEROS5
    449 		if (login_krb5_get_tickets &&
    450 		    k5login(pwd, instance, localhost, p) == 0) {
    451 			rval = 0;
    452 			got_tickets = 1;
    453 		}
    454 #endif
    455 #if defined(KERBEROS) || defined(KERBEROS5)
    456 		if (got_tickets)
    457 			goto skip;
    458 #endif
    459 #ifdef SKEY
    460 		if (skey_haskey(username) == 0 &&
    461 		    skey_passcheck(username, p) != -1) {
    462 			rval = 0;
    463 			goto skip;
    464 		}
    465 #endif
    466 		if (!sflag && *pwd->pw_passwd != '\0' &&
    467 		    !strcmp(crypt(p, pwd->pw_passwd), pwd->pw_passwd)) {
    468 			rval = 0;
    469 			require_chpass = 1;
    470 			goto skip;
    471 		}
    472 		rval = 1;
    473 
    474 	skip:
    475 		memset(p, 0, strlen(p));
    476 
    477 		(void)setpriority(PRIO_PROCESS, 0, 0);
    478 
    479 	ttycheck:
    480 		/*
    481 		 * If trying to log in as root without Kerberos,
    482 		 * but with insecure terminal, refuse the login attempt.
    483 		 */
    484 		if (pwd && !rval && rootlogin && !rootterm(tty)) {
    485 			(void)fprintf(stderr,
    486 			    "%s login refused on this terminal.\n",
    487 			    pwd->pw_name);
    488 			if (hostname)
    489 				syslog(LOG_NOTICE,
    490 				    "LOGIN %s REFUSED FROM %s ON TTY %s",
    491 				    pwd->pw_name, hostname, tty);
    492 			else
    493 				syslog(LOG_NOTICE,
    494 				    "LOGIN %s REFUSED ON TTY %s",
    495 				     pwd->pw_name, tty);
    496 			continue;
    497 		}
    498 
    499 		if (pwd && !rval)
    500 			break;
    501 
    502 		(void)printf("Login incorrect\n");
    503 		failures++;
    504 		cnt++;
    505 		/* we allow 10 tries, but after 3 we start backing off */
    506 		if (cnt > login_backoff) {
    507 			if (cnt >= login_retries) {
    508 				badlogin(username);
    509 				sleepexit(1);
    510 			}
    511 			sleep((u_int)((cnt - 3) * 5));
    512 		}
    513 	}
    514 
    515 	/* committed to login -- turn off timeout */
    516 	(void)alarm((u_int)0);
    517 
    518 	endpwent();
    519 
    520 	/* if user not super-user, check for disabled logins */
    521 #ifdef LOGIN_CAP
    522         if (!login_getcapbool(lc, "ignorenologin", rootlogin))
    523 		checknologin(login_getcapstr(lc, "nologin", NULL, NULL));
    524 #else
    525         if (!rootlogin)
    526                 checknologin(NULL);
    527 #endif
    528 
    529 #ifdef LOGIN_CAP
    530         quietlog = login_getcapbool(lc, "hushlogin", 0);
    531 #else
    532         quietlog = 0;
    533 #endif
    534 	/* Temporarily give up special privileges so we can change */
    535 	/* into NFS-mounted homes that are exported for non-root */
    536 	/* access and have mode 7x0 */
    537 	saved_uid = geteuid();
    538 	saved_gid = getegid();
    539 	nsaved_gids = getgroups(NGROUPS_MAX, saved_gids);
    540 
    541 	(void)setegid(pwd->pw_gid);
    542 	initgroups(username, pwd->pw_gid);
    543 	(void)seteuid(pwd->pw_uid);
    544 
    545 	if (chdir(pwd->pw_dir) < 0) {
    546 #ifdef LOGIN_CAP
    547                 if (login_getcapbool(lc, "requirehome", 0)) {
    548 			(void)printf("Home directory %s required\n",
    549 			    pwd->pw_dir);
    550                         sleepexit(1);
    551 		}
    552 #endif
    553 		(void)printf("No home directory %s!\n", pwd->pw_dir);
    554 		if (chdir("/"))
    555 			exit(0);
    556 		pwd->pw_dir = "/";
    557 		(void)printf("Logging in with home = \"/\".\n");
    558 	}
    559 
    560 	if (!quietlog)
    561 		quietlog = access(_PATH_HUSHLOGIN, F_OK) == 0;
    562 
    563 	/* regain special privileges */
    564 	(void)seteuid(saved_uid);
    565 	setgroups(nsaved_gids, saved_gids);
    566 	(void)setegid(saved_gid);
    567 
    568 #ifdef LOGIN_CAP
    569         pw_warntime = login_getcaptime(lc, "password-warn",
    570             _PASSWORD_WARNDAYS * SECSPERDAY,
    571             _PASSWORD_WARNDAYS * SECSPERDAY);
    572 #endif
    573 
    574 	(void)gettimeofday(&now, (struct timezone *)NULL);
    575 	if (pwd->pw_expire) {
    576 		if (now.tv_sec >= pwd->pw_expire) {
    577 			(void)printf("Sorry -- your account has expired.\n");
    578 			sleepexit(1);
    579 		} else if (pwd->pw_expire - now.tv_sec < pw_warntime &&
    580 		    !quietlog)
    581 			(void)printf("Warning: your account expires on %s",
    582 			    ctime(&pwd->pw_expire));
    583 	}
    584 	if (pwd->pw_change) {
    585 		if (pwd->pw_change == _PASSWORD_CHGNOW)
    586 			need_chpass = 1;
    587 		else if (now.tv_sec >= pwd->pw_change) {
    588 			(void)printf("Sorry -- your password has expired.\n");
    589 			sleepexit(1);
    590 		} else if (pwd->pw_change - now.tv_sec < pw_warntime &&
    591 		    !quietlog)
    592 			(void)printf("Warning: your password expires on %s",
    593 			    ctime(&pwd->pw_change));
    594 
    595 	}
    596 	/* Nothing else left to fail -- really log in. */
    597 	update_db(quietlog);
    598 
    599 	(void)chown(ttyn, pwd->pw_uid,
    600 	    (gr = getgrnam(TTYGRPNAME)) ? gr->gr_gid : pwd->pw_gid);
    601 
    602 	if (ttyaction(ttyn, "login", pwd->pw_name))
    603 		(void)printf("Warning: ttyaction failed.\n");
    604 
    605 #if defined(KERBEROS) || defined(KERBEROS5)
    606 	/* Fork so that we can call kdestroy */
    607 	if (
    608 #ifdef KERBEROS5
    609 	    ! login_krb5_retain_ccache &&
    610 #endif
    611 	    has_ccache)
    612 		dofork();
    613 #endif
    614 
    615 	/* Destroy environment unless user has requested its preservation. */
    616 	if (!pflag)
    617 		environ = envinit;
    618 
    619 #ifdef LOGIN_CAP
    620 	if (nested == NULL && setusercontext(lc, pwd, pwd->pw_uid,
    621 	    LOGIN_SETLOGIN) != 0) {
    622 		syslog(LOG_ERR, "setusercontext failed");
    623 		exit(1);
    624 	}
    625 	if (setusercontext(lc, pwd, pwd->pw_uid,
    626 	    (LOGIN_SETALL & ~(LOGIN_SETPATH|LOGIN_SETLOGIN))) != 0) {
    627 		syslog(LOG_ERR, "setusercontext failed");
    628 		exit(1);
    629 	}
    630 #else
    631 	(void)setgid(pwd->pw_gid);
    632 
    633 	initgroups(username, pwd->pw_gid);
    634 
    635 	if (nested == NULL && setlogin(pwd->pw_name) < 0)
    636 		syslog(LOG_ERR, "setlogin() failure: %m");
    637 
    638 	/* Discard permissions last so can't get killed and drop core. */
    639 	if (rootlogin)
    640 		(void)setuid(0);
    641 	else
    642 		(void)setuid(pwd->pw_uid);
    643 #endif
    644 
    645 	if (*pwd->pw_shell == '\0')
    646 		pwd->pw_shell = _PATH_BSHELL;
    647 #ifdef LOGIN_CAP
    648 	if ((shell = login_getcapstr(lc, "shell", NULL, NULL)) != NULL) {
    649 		if ((shell = strdup(shell)) == NULL) {
    650                 	syslog(LOG_ERR, "Cannot alloc mem");
    651                 	sleepexit(1);
    652 		}
    653 		pwd->pw_shell = shell;
    654 	}
    655 #endif
    656 
    657 	(void)setenv("HOME", pwd->pw_dir, 1);
    658 	(void)setenv("SHELL", pwd->pw_shell, 1);
    659 	if (term[0] == '\0') {
    660 		char *tt = (char *)stypeof(tty);
    661 #ifdef LOGIN_CAP
    662 		if (tt == NULL)
    663 			tt = login_getcapstr(lc, "term", NULL, NULL);
    664 #endif
    665 		/* unknown term -> "su" */
    666 		(void)strlcpy(term, tt != NULL ? tt : "su", sizeof(term));
    667 	}
    668 	(void)setenv("TERM", term, 0);
    669 	(void)setenv("LOGNAME", pwd->pw_name, 1);
    670 	(void)setenv("USER", pwd->pw_name, 1);
    671 
    672 #ifdef LOGIN_CAP
    673 	setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETPATH);
    674 #else
    675 	(void)setenv("PATH", _PATH_DEFPATH, 0);
    676 #endif
    677 
    678 #ifdef KERBEROS
    679 	if (krbtkfile_env)
    680 		(void)setenv("KRBTKFILE", krbtkfile_env, 1);
    681 #endif
    682 #ifdef KERBEROS5
    683 	if (krb5tkfile_env)
    684 		(void)setenv("KRB5CCNAME", krb5tkfile_env, 1);
    685 #endif
    686 
    687 	if (tty[sizeof("tty")-1] == 'd')
    688 		syslog(LOG_INFO, "DIALUP %s, %s", tty, pwd->pw_name);
    689 
    690 	/* If fflag is on, assume caller/authenticator has logged root login. */
    691 	if (rootlogin && fflag == 0) {
    692 		if (hostname)
    693 			syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s FROM %s",
    694 			    username, tty, hostname);
    695 		else
    696 			syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s",
    697 			    username, tty);
    698 	}
    699 
    700 #if defined(KERBEROS) || defined(KERBEROS5)
    701 	if (KERBEROS_CONFIGURED && !quietlog && notickets == 1)
    702 		(void)printf("Warning: no Kerberos tickets issued.\n");
    703 #endif
    704 
    705 	if (!quietlog) {
    706 		char *fname;
    707 #ifdef LOGIN_CAP
    708 		fname = login_getcapstr(lc, "copyright", NULL, NULL);
    709 		if (fname != NULL && access(fname, F_OK) == 0)
    710 			motd(fname);
    711 		else
    712 #endif
    713 			(void)printf("%s", copyrightstr);
    714 
    715 #ifdef LOGIN_CAP
    716                 fname = login_getcapstr(lc, "welcome", NULL, NULL);
    717                 if (fname == NULL || access(fname, F_OK) != 0)
    718 #endif
    719                         fname = _PATH_MOTDFILE;
    720                 motd(fname);
    721 
    722 		(void)snprintf(tbuf,
    723 		    sizeof(tbuf), "%s/%s", _PATH_MAILDIR, pwd->pw_name);
    724 		if (stat(tbuf, &st) == 0 && st.st_size != 0)
    725 			(void)printf("You have %smail.\n",
    726 			    (st.st_mtime > st.st_atime) ? "new " : "");
    727 	}
    728 
    729 #ifdef LOGIN_CAP
    730 	login_close(lc);
    731 #endif
    732 
    733 	(void)signal(SIGALRM, SIG_DFL);
    734 	(void)signal(SIGQUIT, SIG_DFL);
    735 	(void)signal(SIGINT, SIG_DFL);
    736 	(void)signal(SIGTSTP, SIG_IGN);
    737 
    738 	tbuf[0] = '-';
    739 	(void)strlcpy(tbuf + 1, (p = strrchr(pwd->pw_shell, '/')) ?
    740 	    p + 1 : pwd->pw_shell, sizeof(tbuf) - 1);
    741 
    742 	/* Wait to change password until we're unprivileged */
    743 	if (need_chpass) {
    744 		if (!require_chpass)
    745 			(void)printf(
    746 "Warning: your password has expired. Please change it as soon as possible.\n");
    747 		else {
    748 			int	status;
    749 
    750 			(void)printf(
    751 		    "Your password has expired. Please choose a new one.\n");
    752 			switch (fork()) {
    753 			case -1:
    754 				warn("fork");
    755 				sleepexit(1);
    756 			case 0:
    757 				execl(_PATH_BINPASSWD, "passwd", 0);
    758 				_exit(1);
    759 			default:
    760 				if (wait(&status) == -1 ||
    761 				    WEXITSTATUS(status))
    762 					sleepexit(1);
    763 			}
    764 		}
    765 	}
    766 
    767 #ifdef KERBEROS5
    768 	if (login_krb5_get_tickets)
    769 		k5_write_creds();
    770 #endif
    771 	execlp(pwd->pw_shell, tbuf, 0);
    772 	err(1, "%s", pwd->pw_shell);
    773 }
    774 
    775 #if defined(KERBEROS) || defined(KERBEROS5)
    776 #define	NBUFSIZ		(MAXLOGNAME + 1 + 5)	/* .root suffix */
    777 #else
    778 #define	NBUFSIZ		(MAXLOGNAME + 1)
    779 #endif
    780 
    781 #if defined(KERBEROS) || defined(KERBEROS5)
    782 /*
    783  * This routine handles cleanup stuff, and the like.
    784  * It exists only in the child process.
    785  */
    786 #include <sys/wait.h>
    787 void
    788 dofork()
    789 {
    790 	int child;
    791 
    792 	if (!(child = fork()))
    793 		return; /* Child process */
    794 
    795 	/*
    796 	 * Setup stuff?  This would be things we could do in parallel
    797 	 * with login
    798 	 */
    799 	(void)chdir("/");	/* Let's not keep the fs busy... */
    800 
    801 	/* If we're the parent, watch the child until it dies */
    802 	while (wait(0) != child)
    803 		;
    804 
    805 	/* Cleanup stuff */
    806 	/* Run kdestroy to destroy tickets */
    807 #ifdef KERBEROS
    808 	kdestroy();
    809 #endif
    810 #ifdef KERBEROS5
    811 	if (login_krb5_get_tickets)
    812 		k5destroy();
    813 #endif
    814 
    815 	/* Leave */
    816 	exit(0);
    817 }
    818 #endif
    819 
    820 void
    821 getloginname()
    822 {
    823 	int ch;
    824 	char *p;
    825 	static char nbuf[NBUFSIZ];
    826 
    827 	for (;;) {
    828 		(void)printf("login: ");
    829 		for (p = nbuf; (ch = getchar()) != '\n'; ) {
    830 			if (ch == EOF) {
    831 				badlogin(username);
    832 				exit(0);
    833 			}
    834 			if (p < nbuf + (NBUFSIZ - 1))
    835 				*p++ = ch;
    836 		}
    837 		if (p > nbuf) {
    838 			if (nbuf[0] == '-')
    839 				(void)fprintf(stderr,
    840 				    "login names may not start with '-'.\n");
    841 			else {
    842 				*p = '\0';
    843 				username = nbuf;
    844 				break;
    845 			}
    846 		}
    847 	}
    848 }
    849 
    850 int
    851 rootterm(ttyn)
    852 	char *ttyn;
    853 {
    854 	struct ttyent *t;
    855 
    856 	return ((t = getttynam(ttyn)) && t->ty_status & TTY_SECURE);
    857 }
    858 
    859 jmp_buf motdinterrupt;
    860 
    861 void
    862 motd(fname)
    863 	char *fname;
    864 {
    865 	int fd, nchars;
    866 	sig_t oldint;
    867 	char tbuf[8192];
    868 
    869 	if ((fd = open(fname ? fname : _PATH_MOTDFILE, O_RDONLY, 0)) < 0)
    870 		return;
    871 	oldint = signal(SIGINT, sigint);
    872 	if (setjmp(motdinterrupt) == 0)
    873 		while ((nchars = read(fd, tbuf, sizeof(tbuf))) > 0)
    874 			(void)write(fileno(stdout), tbuf, nchars);
    875 	(void)signal(SIGINT, oldint);
    876 	(void)close(fd);
    877 }
    878 
    879 /* ARGSUSED */
    880 void
    881 sigint(signo)
    882 	int signo;
    883 {
    884 
    885 	longjmp(motdinterrupt, 1);
    886 }
    887 
    888 /* ARGSUSED */
    889 void
    890 timedout(signo)
    891 	int signo;
    892 {
    893 
    894 	(void)fprintf(stderr, "Login timed out after %d seconds\n", timeout);
    895 	exit(0);
    896 }
    897 
    898 void
    899 checknologin(fname)
    900 	char *fname;
    901 {
    902 	int fd, nchars;
    903 	char tbuf[8192];
    904 
    905 	if ((fd = open(fname ? fname : _PATH_NOLOGIN, O_RDONLY, 0)) >= 0) {
    906 		while ((nchars = read(fd, tbuf, sizeof(tbuf))) > 0)
    907 			(void)write(fileno(stdout), tbuf, nchars);
    908 		sleepexit(0);
    909 	}
    910 }
    911 
    912 static void
    913 update_db(int quietlog)
    914 {
    915 	if (nested != NULL) {
    916 		if (hostname != NULL)
    917 			syslog(LOG_NOTICE, "%s to %s on tty %s from %s",
    918 			    nested, pwd->pw_name, tty, hostname);
    919 		else
    920 			syslog(LOG_NOTICE, "%s to %s on tty %s", nested,
    921 			    pwd->pw_name, tty);
    922 
    923 		return;
    924 	}
    925 	if (hostname != NULL) {
    926 		socklen_t len = sizeof(ss);
    927 		(void)getpeername(STDIN_FILENO, (struct sockaddr *)&ss, &len);
    928 	}
    929 	(void)gettimeofday(&now, NULL);
    930 #ifdef SUPPORT_UTMPX
    931 	doutmpx();
    932 	dolastlogx(quietlog);
    933 	quietlog = 1;
    934 #endif
    935 #ifdef SUPPORT_UTMP
    936 	doutmp();
    937 	dolastlog(quietlog);
    938 #endif
    939 }
    940 
    941 #ifdef SUPPORT_UTMPX
    942 static void
    943 doutmpx()
    944 {
    945 	struct utmpx utmpx;
    946 	char *t;
    947 
    948 	memset((void *)&utmpx, 0, sizeof(utmpx));
    949 	utmpx.ut_tv = now;
    950 	(void)strncpy(utmpx.ut_name, username, sizeof(utmpx.ut_name));
    951 	if (hostname) {
    952 		(void)strncpy(utmpx.ut_host, hostname, sizeof(utmpx.ut_host));
    953 		utmpx.ut_ss = ss;
    954 	}
    955 	(void)strncpy(utmpx.ut_line, tty, sizeof(utmpx.ut_line));
    956 	utmpx.ut_type = USER_PROCESS;
    957 	utmpx.ut_pid = getpid();
    958 	t = tty + strlen(tty);
    959 	if (t - tty >= sizeof(utmpx.ut_id)) {
    960 	    (void)strncpy(utmpx.ut_id, t - sizeof(utmpx.ut_id),
    961 		sizeof(utmpx.ut_id));
    962 	} else {
    963 	    (void)strncpy(utmpx.ut_id, tty, sizeof(utmpx.ut_id));
    964 	}
    965 	if (pututxline(&utmpx) == NULL)
    966 		syslog(LOG_NOTICE, "Cannot update utmpx %m");
    967 	endutxent();
    968 	if (updwtmpx(_PATH_WTMPX, &utmpx) != 0)
    969 		syslog(LOG_NOTICE, "Cannot update wtmpx %m");
    970 }
    971 
    972 static void
    973 dolastlogx(quiet)
    974 	int quiet;
    975 {
    976 	struct lastlogx ll;
    977 	if (getlastlogx(_PATH_LASTLOGX, pwd->pw_uid, &ll) != NULL) {
    978 		time_t t = (time_t)ll.ll_tv.tv_sec;
    979 		(void)printf("Last login: %.24s ", ctime(&t));
    980 		if (*ll.ll_host != '\0')
    981 			(void)printf("from %.*s ",
    982 			    (int)sizeof(ll.ll_host),
    983 			    ll.ll_host);
    984 		(void)printf("on %.*s\n",
    985 		    (int)sizeof(ll.ll_line),
    986 		    ll.ll_line);
    987 	}
    988 	ll.ll_tv = now;
    989 	(void)strncpy(ll.ll_line, tty, sizeof(ll.ll_line));
    990 	if (hostname) {
    991 		(void)strncpy(ll.ll_host, hostname, sizeof(ll.ll_host));
    992 		ll.ll_ss = ss;
    993 	}
    994 	if (updlastlogx(_PATH_LASTLOGX, pwd->pw_uid, &ll) != 0)
    995 		syslog(LOG_NOTICE, "Cannot update lastlogx %m");
    996 }
    997 #endif
    998 
    999 #ifdef SUPPORT_UTMP
   1000 static void
   1001 doutmp()
   1002 {
   1003 	struct utmp utmp;
   1004 
   1005 	(void)memset((void *)&utmp, 0, sizeof(utmp));
   1006 	utmp.ut_time = now.tv_sec;
   1007 	(void)strncpy(utmp.ut_name, username, sizeof(utmp.ut_name));
   1008 	if (hostname)
   1009 		(void)strncpy(utmp.ut_host, hostname, sizeof(utmp.ut_host));
   1010 	(void)strncpy(utmp.ut_line, tty, sizeof(utmp.ut_line));
   1011 	login(&utmp);
   1012 }
   1013 
   1014 static void
   1015 dolastlog(quiet)
   1016 	int quiet;
   1017 {
   1018 	struct lastlog ll;
   1019 	int fd;
   1020 
   1021 	if ((fd = open(_PATH_LASTLOG, O_RDWR, 0)) >= 0) {
   1022 		(void)lseek(fd, (off_t)(pwd->pw_uid * sizeof(ll)), SEEK_SET);
   1023 		if (!quiet) {
   1024 			if (read(fd, (char *)&ll, sizeof(ll)) == sizeof(ll) &&
   1025 			    ll.ll_time != 0) {
   1026 				(void)printf("Last login: %.24s ",
   1027 				    ctime(&ll.ll_time));
   1028 				if (*ll.ll_host != '\0')
   1029 					(void)printf("from %.*s ",
   1030 					    (int)sizeof(ll.ll_host),
   1031 					    ll.ll_host);
   1032 				(void)printf("on %.*s\n",
   1033 				    (int)sizeof(ll.ll_line), ll.ll_line);
   1034 			}
   1035 			(void)lseek(fd, (off_t)(pwd->pw_uid * sizeof(ll)),
   1036 			    SEEK_SET);
   1037 		}
   1038 		memset((void *)&ll, 0, sizeof(ll));
   1039 		ll.ll_time = now.tv_sec;
   1040 		(void)strncpy(ll.ll_line, tty, sizeof(ll.ll_line));
   1041 		if (hostname)
   1042 			(void)strncpy(ll.ll_host, hostname, sizeof(ll.ll_host));
   1043 		(void)write(fd, (char *)&ll, sizeof(ll));
   1044 		(void)close(fd);
   1045 	}
   1046 }
   1047 #endif
   1048 
   1049 void
   1050 badlogin(name)
   1051 	char *name;
   1052 {
   1053 
   1054 	if (failures == 0)
   1055 		return;
   1056 	if (hostname) {
   1057 		syslog(LOG_NOTICE, "%d LOGIN FAILURE%s FROM %s",
   1058 		    failures, failures > 1 ? "S" : "", hostname);
   1059 		syslog(LOG_AUTHPRIV|LOG_NOTICE,
   1060 		    "%d LOGIN FAILURE%s FROM %s, %s",
   1061 		    failures, failures > 1 ? "S" : "", hostname, name);
   1062 	} else {
   1063 		syslog(LOG_NOTICE, "%d LOGIN FAILURE%s ON %s",
   1064 		    failures, failures > 1 ? "S" : "", tty);
   1065 		syslog(LOG_AUTHPRIV|LOG_NOTICE,
   1066 		    "%d LOGIN FAILURE%s ON %s, %s",
   1067 		    failures, failures > 1 ? "S" : "", tty, name);
   1068 	}
   1069 }
   1070 
   1071 const char *
   1072 stypeof(ttyid)
   1073 	const char *ttyid;
   1074 {
   1075 	struct ttyent *t;
   1076 
   1077 	return (ttyid && (t = getttynam(ttyid)) ? t->ty_type : NULL);
   1078 }
   1079 
   1080 void
   1081 sleepexit(eval)
   1082 	int eval;
   1083 {
   1084 
   1085 	(void)sleep(5);
   1086 	exit(eval);
   1087 }
   1088