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