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