login.c revision 86450
1/*-
2 * Copyright (c) 1980, 1987, 1988, 1991, 1993, 1994
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#if 0
35static char copyright[] =
36"@(#) Copyright (c) 1980, 1987, 1988, 1991, 1993, 1994\n\
37	The Regents of the University of California.  All rights reserved.\n";
38#endif
39
40#ifndef lint
41#if 0
42static char sccsid[] = "@(#)login.c	8.4 (Berkeley) 4/2/94";
43#endif
44static const char rcsid[] =
45  "$FreeBSD: head/usr.bin/login/login.c 86450 2001-11-16 04:39:16Z rwatson $";
46#endif /* not lint */
47
48/*
49 * login [ name ]
50 * login -h hostname	(for telnetd, etc.)
51 * login -f name	(for pre-authenticated login: datakit, xterm, etc.)
52 */
53
54#include <sys/copyright.h>
55#include <sys/param.h>
56#include <sys/stat.h>
57#include <sys/socket.h>
58#include <sys/time.h>
59#include <sys/resource.h>
60#include <sys/file.h>
61#include <netinet/in.h>
62#include <arpa/inet.h>
63
64#include <err.h>
65#include <errno.h>
66#include <grp.h>
67#include <libutil.h>
68#include <login_cap.h>
69#include <netdb.h>
70#include <pwd.h>
71#include <setjmp.h>
72#include <signal.h>
73#include <stdio.h>
74#include <stdlib.h>
75#include <string.h>
76#include <syslog.h>
77#include <ttyent.h>
78#include <unistd.h>
79#include <utmp.h>
80
81#include <security/pam_appl.h>
82#include <security/pam_misc.h>
83#include <sys/wait.h>
84
85#include "pathnames.h"
86
87/* wrapper for KAME-special getnameinfo() */
88#ifndef NI_WITHSCOPEID
89#define	NI_WITHSCOPEID	0
90#endif
91
92void	 badlogin __P((char *));
93void	 dolastlog __P((int));
94void	 getloginname __P((void));
95void	 motd __P((char *));
96int	 rootterm __P((char *));
97void	 sigint __P((int));
98void	 sleepexit __P((int));
99void	 refused __P((char *,char *,int));
100char	*stypeof __P((char *));
101void	 timedout __P((int));
102int	 login_access __P((char *, char *));
103void     login_fbtab __P((char *, uid_t, gid_t));
104
105static int auth_pam __P((void));
106static int export_pam_environment __P((void));
107static int ok_to_export __P((const char *));
108
109static pam_handle_t *pamh = NULL;
110static char **environ_pam;
111
112#define PAM_END { \
113	if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS) \
114		syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e)); \
115	if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS) \
116		syslog(LOG_ERR, "pam_close_session: %s", pam_strerror(pamh, e)); \
117	if ((e = pam_end(pamh, e)) != PAM_SUCCESS) \
118		syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e)); \
119}
120
121static int auth_traditional __P((void));
122extern void login __P((struct utmp *));
123static void usage __P((void));
124
125#define	TTYGRPNAME	"tty"		/* name of group to own ttys */
126#define	DEFAULT_BACKOFF	3
127#define	DEFAULT_RETRIES	10
128#define	DEFAULT_PROMPT		"login: "
129#define	DEFAULT_PASSWD_PROMPT	"Password:"
130
131/*
132 * This bounds the time given to login.  Not a define so it can
133 * be patched on machines where it's too small.
134 */
135u_int	timeout = 300;
136
137/* Buffer for signal handling of timeout */
138jmp_buf timeout_buf;
139
140struct	passwd *pwd;
141int	failures;
142char	*term, *envinit[1], *hostname, *passwd_prompt, *prompt, *tty, *username;
143char    full_hostname[MAXHOSTNAMELEN];
144
145int
146main(argc, argv)
147	int argc;
148	char *argv[];
149{
150	extern char **environ;
151	struct group *gr;
152	struct stat st;
153	struct timeval tp;
154	struct utmp utmp;
155	int rootok, retries, backoff;
156	int ask, ch, cnt, fflag, hflag, pflag, quietlog, rootlogin, rval;
157	time_t warntime;
158	uid_t uid, euid;
159	gid_t egid;
160	char *p, *ttyn;
161	char tbuf[MAXPATHLEN + 2];
162	char tname[sizeof(_PATH_TTY) + 10];
163	char *shell = NULL;
164	login_cap_t *lc = NULL;
165	pid_t pid;
166	int e;
167
168	(void)signal(SIGQUIT, SIG_IGN);
169	(void)signal(SIGINT, SIG_IGN);
170	(void)signal(SIGHUP, SIG_IGN);
171	if (setjmp(timeout_buf)) {
172		if (failures)
173			badlogin(tbuf);
174		(void)fprintf(stderr, "Login timed out after %d seconds\n",
175		    timeout);
176		exit(0);
177	}
178	(void)signal(SIGALRM, timedout);
179	(void)alarm(timeout);
180	(void)setpriority(PRIO_PROCESS, 0, 0);
181
182	openlog("login", LOG_ODELAY, LOG_AUTH);
183
184	/*
185	 * -p is used by getty to tell login not to destroy the environment
186	 * -f is used to skip a second login authentication
187	 * -h is used by other servers to pass the name of the remote
188	 *    host to login so that it may be placed in utmp and wtmp
189	 */
190	*full_hostname = '\0';
191	term = NULL;
192
193	fflag = hflag = pflag = 0;
194	uid = getuid();
195	euid = geteuid();
196	egid = getegid();
197	while ((ch = getopt(argc, argv, "fh:p")) != -1)
198		switch (ch) {
199		case 'f':
200			fflag = 1;
201			break;
202		case 'h':
203			if (uid)
204				errx(1, "-h option: %s", strerror(EPERM));
205			hflag = 1;
206			if (strlcpy(full_hostname, optarg,
207			    sizeof(full_hostname)) >= sizeof(full_hostname))
208				errx(1, "-h option: %s: exceeds maximum "
209				    "hostname size", optarg);
210
211			trimdomain(optarg, UT_HOSTSIZE);
212
213			if (strlen(optarg) > UT_HOSTSIZE) {
214				struct addrinfo hints, *res;
215				int ga_err;
216
217				memset(&hints, 0, sizeof(hints));
218				hints.ai_family = AF_UNSPEC;
219				ga_err = getaddrinfo(optarg, NULL, &hints,
220				    &res);
221				if (ga_err == 0) {
222					char hostbuf[MAXHOSTNAMELEN];
223
224					getnameinfo(res->ai_addr,
225					    res->ai_addrlen,
226					    hostbuf,
227					    sizeof(hostbuf), NULL, 0,
228					    NI_NUMERICHOST|
229					    NI_WITHSCOPEID);
230					optarg = strdup(hostbuf);
231					if (optarg == NULL) {
232						syslog(LOG_NOTICE,
233						    "strdup(): %m");
234						sleepexit(1);
235					}
236				} else
237					optarg = "invalid hostname";
238				if (res != NULL)
239					freeaddrinfo(res);
240			}
241			hostname = optarg;
242			break;
243		case 'p':
244			pflag = 1;
245			break;
246		case '?':
247		default:
248			if (!uid)
249				syslog(LOG_ERR, "invalid flag %c", ch);
250			usage();
251		}
252	argc -= optind;
253	argv += optind;
254
255	if (*argv) {
256		username = *argv;
257		ask = 0;
258	} else
259		ask = 1;
260
261	for (cnt = getdtablesize(); cnt > 2; cnt--)
262		(void)close(cnt);
263
264	ttyn = ttyname(STDIN_FILENO);
265	if (ttyn == NULL || *ttyn == '\0') {
266		(void)snprintf(tname, sizeof(tname), "%s??", _PATH_TTY);
267		ttyn = tname;
268	}
269	if ((tty = strrchr(ttyn, '/')) != NULL)
270		++tty;
271	else
272		tty = ttyn;
273
274	/*
275	 * Get "login-retries" & "login-backoff" from default class
276	 */
277	lc = login_getclass(NULL);
278	prompt = login_getcapstr(lc, "prompt", DEFAULT_PROMPT, DEFAULT_PROMPT);
279	passwd_prompt = login_getcapstr(lc, "passwd_prompt",
280	    DEFAULT_PASSWD_PROMPT, DEFAULT_PASSWD_PROMPT);
281	retries = login_getcapnum(lc, "login-retries", DEFAULT_RETRIES,
282	    DEFAULT_RETRIES);
283	backoff = login_getcapnum(lc, "login-backoff", DEFAULT_BACKOFF,
284	    DEFAULT_BACKOFF);
285	login_close(lc);
286	lc = NULL;
287
288	for (cnt = 0;; ask = 1) {
289		if (ask) {
290			fflag = 0;
291			getloginname();
292		}
293		rootlogin = 0;
294		rootok = rootterm(tty); /* Default (auth may change) */
295
296		if (strlen(username) > UT_NAMESIZE)
297			username[UT_NAMESIZE] = '\0';
298
299		/*
300		 * Note if trying multiple user names; log failures for
301		 * previous user name, but don't bother logging one failure
302		 * for nonexistent name (mistyped username).
303		 */
304		if (failures && strcmp(tbuf, username)) {
305			if (failures > (pwd ? 0 : 1))
306				badlogin(tbuf);
307		}
308		(void)strlcpy(tbuf, username, sizeof(tbuf));
309
310		pwd = getpwnam(username);
311
312		/*
313		 * if we have a valid account name, and it doesn't have a
314		 * password, or the -f option was specified and the caller
315		 * is root or the caller isn't changing their uid, don't
316		 * authenticate.
317		 */
318		if (pwd != NULL) {
319			if (pwd->pw_uid == 0)
320				rootlogin = 1;
321
322			if (fflag && (uid == (uid_t)0 ||
323			    uid == (uid_t)pwd->pw_uid)) {
324				/* already authenticated */
325				break;
326			} else if (pwd->pw_passwd[0] == '\0') {
327				if (!rootlogin || rootok) {
328					/* pretend password okay */
329					rval = 0;
330					goto ttycheck;
331				}
332			}
333		}
334
335		fflag = 0;
336
337		(void)setpriority(PRIO_PROCESS, 0, -4);
338
339		/*
340		 * Try to authenticate using PAM.  If a PAM system error
341		 * occurs, perhaps because of a botched configuration,
342		 * then fall back to using traditional Unix authentication.
343		 */
344		if ((rval = auth_pam()) == -1)
345			rval = auth_traditional();
346
347		(void)setpriority(PRIO_PROCESS, 0, 0);
348
349		/*
350		 * PAM authentication may have changed "pwd" to the
351		 * entry for the template user.  Check again to see if
352		 * this is a root login after all.
353		 */
354		if (pwd != NULL && pwd->pw_uid == 0)
355			rootlogin = 1;
356
357	ttycheck:
358		/*
359		 * If trying to log in as root without Kerberos,
360		 * but with insecure terminal, refuse the login attempt.
361		 */
362		if (pwd && !rval) {
363			if (rootlogin && !rootok)
364				refused(NULL, "NOROOT", 0);
365			else	/* valid password & authenticated */
366				break;
367		}
368
369		(void)printf("Login incorrect\n");
370		failures++;
371
372		/*
373		 * we allow up to 'retry' (10) tries,
374		 * but after 'backoff' (3) we start backing off
375		 */
376		if (++cnt > backoff) {
377			if (cnt >= retries) {
378				badlogin(username);
379				sleepexit(1);
380			}
381			sleep((u_int)((cnt - backoff) * 5));
382		}
383	}
384
385	/* committed to login -- turn off timeout */
386	(void)alarm((u_int)0);
387	(void)signal(SIGHUP, SIG_DFL);
388
389	endpwent();
390
391	/*
392	 * Establish the login class.
393	 */
394	lc = login_getpwclass(pwd);
395
396	quietlog = login_getcapbool(lc, "hushlogin", 0);
397	/*
398	 * Switching needed for NFS with root access disabled.
399	 *
400	 * XXX: This change fails to modify the additional groups for the
401	 * process, and as such, may restrict rights normally granted
402	 * through those groups.
403	 */
404	(void)setegid(pwd->pw_gid);
405	(void)seteuid(rootlogin ? 0 : pwd->pw_uid);
406	if (!*pwd->pw_dir || chdir(pwd->pw_dir) < 0) {
407		if (login_getcapbool(lc, "requirehome", 0))
408			refused("Home directory not available", "HOMEDIR", 1);
409		if (chdir("/") < 0)
410			refused("Cannot find root directory", "ROOTDIR", 1);
411		if (!quietlog || *pwd->pw_dir)
412			printf("No home directory.\nLogging in with home = \"/\".\n");
413		pwd->pw_dir = "/";
414	}
415	(void)seteuid(euid);
416	(void)setegid(egid);
417	if (!quietlog)
418		quietlog = access(_PATH_HUSHLOGIN, F_OK) == 0;
419
420	if (pwd->pw_change || pwd->pw_expire)
421		(void)gettimeofday(&tp, (struct timezone *)NULL);
422
423#define	DEFAULT_WARN  (2L * 7L * 86400L)  /* Two weeks */
424
425	warntime = login_getcaptime(lc, "warnexpire", DEFAULT_WARN,
426	    DEFAULT_WARN);
427
428	if (pwd->pw_expire) {
429		if (tp.tv_sec >= pwd->pw_expire) {
430			refused("Sorry -- your account has expired", "EXPIRED",
431			    1);
432		} else if (pwd->pw_expire - tp.tv_sec < warntime && !quietlog)
433			(void)printf("Warning: your account expires on %s",
434			    ctime(&pwd->pw_expire));
435	}
436
437	if (lc != NULL) {
438		if (hostname) {
439			struct addrinfo hints, *res;
440			int ga_err;
441
442			memset(&hints, 0, sizeof(hints));
443			hints.ai_family = AF_UNSPEC;
444			ga_err = getaddrinfo(full_hostname, NULL, &hints,
445					     &res);
446			if (ga_err == 0) {
447				char hostbuf[MAXHOSTNAMELEN];
448
449				getnameinfo(res->ai_addr, res->ai_addrlen,
450				    hostbuf, sizeof(hostbuf), NULL, 0,
451				    NI_NUMERICHOST|NI_WITHSCOPEID);
452				if ((optarg = strdup(hostbuf)) == NULL) {
453					syslog(LOG_NOTICE, "strdup(): %m");
454					sleepexit(1);
455				}
456			} else
457				optarg = NULL;
458			if (res != NULL)
459				freeaddrinfo(res);
460			if (!auth_hostok(lc, full_hostname, optarg))
461				refused("Permission denied", "HOST", 1);
462		}
463
464		if (!auth_ttyok(lc, tty))
465			refused("Permission denied", "TTY", 1);
466
467		if (!auth_timeok(lc, time(NULL)))
468			refused("Logins not available right now", "TIME", 1);
469	}
470        shell = login_getcapstr(lc, "shell", pwd->pw_shell, pwd->pw_shell);
471	if (*pwd->pw_shell == '\0')
472		pwd->pw_shell = _PATH_BSHELL;
473	if (*shell == '\0')   /* Not overridden */
474		shell = pwd->pw_shell;
475	if ((shell = strdup(shell)) == NULL) {
476		syslog(LOG_NOTICE, "strdup(): %m");
477		sleepexit(1);
478	}
479
480#ifdef LOGIN_ACCESS
481	if (login_access(pwd->pw_name, hostname ? full_hostname : tty) == 0)
482		refused("Permission denied", "ACCESS", 1);
483#endif /* LOGIN_ACCESS */
484
485	/* Nothing else left to fail -- really log in. */
486	memset((void *)&utmp, 0, sizeof(utmp));
487	(void)time(&utmp.ut_time);
488	(void)strncpy(utmp.ut_name, username, sizeof(utmp.ut_name));
489	if (hostname)
490		(void)strncpy(utmp.ut_host, hostname, sizeof(utmp.ut_host));
491	(void)strncpy(utmp.ut_line, tty, sizeof(utmp.ut_line));
492	login(&utmp);
493
494	dolastlog(quietlog);
495
496	/*
497	 * Set device protections, depending on what terminal the
498	 * user is logged in. This feature is used on Suns to give
499	 * console users better privacy.
500	 */
501	login_fbtab(tty, pwd->pw_uid, pwd->pw_gid);
502
503	/*
504	 * Clear flags of the tty.  None should be set, and when the
505	 * user sets them otherwise, this can cause the chown to fail.
506	 * Since it isn't clear that flags are useful on character
507	 * devices, we just clear them.
508	 */
509	if (chflags(ttyn, 0) && errno != EOPNOTSUPP)
510		syslog(LOG_ERR, "chmod(%s): %m", ttyn);
511	if (chown(ttyn, pwd->pw_uid,
512	    (gr = getgrnam(TTYGRPNAME)) ? gr->gr_gid : pwd->pw_gid))
513		syslog(LOG_ERR, "chmod(%s): %m", ttyn);
514
515
516	/*
517	 * Preserve TERM if it happens to be already set.
518	 */
519	if ((term = getenv("TERM")) != NULL) {
520		if ((term = strdup(term)) == NULL) {
521			syslog(LOG_NOTICE,
522			    "strdup(): %m");
523			sleepexit(1);
524		}
525	}
526
527	/*
528	 * Exclude cons/vt/ptys only, assume dialup otherwise
529	 * TODO: Make dialup tty determination a library call
530	 * for consistency (finger etc.)
531	 */
532	if (hostname==NULL && isdialuptty(tty))
533		syslog(LOG_INFO, "DIALUP %s, %s", tty, pwd->pw_name);
534
535#ifdef LOGALL
536	/*
537	 * Syslog each successful login, so we don't have to watch hundreds
538	 * of wtmp or lastlogin files.
539	 */
540	if (hostname)
541		syslog(LOG_INFO, "login from %s on %s as %s",
542		       full_hostname, tty, pwd->pw_name);
543	else
544		syslog(LOG_INFO, "login on %s as %s",
545		       tty, pwd->pw_name);
546#endif
547
548	/*
549	 * If fflag is on, assume caller/authenticator has logged root login.
550	 */
551	if (rootlogin && fflag == 0)
552	{
553		if (hostname)
554			syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s FROM %s",
555			    username, tty, full_hostname);
556		else
557			syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s",
558			    username, tty);
559	}
560
561	/*
562	 * Destroy environment unless user has requested its preservation.
563	 * We need to do this before setusercontext() because that may
564	 * set or reset some environment variables.
565	 */
566	if (!pflag)
567		environ = envinit;
568
569	/*
570	 * PAM modules might add supplementary groups during pam_setcred().
571	 */
572	if (setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETGROUP) != 0) {
573                syslog(LOG_ERR, "setusercontext() failed - exiting");
574		exit(1);
575	}
576
577	if (pamh) {
578		if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
579			syslog(LOG_ERR, "pam_open_session: %s",
580			    pam_strerror(pamh, e));
581		} else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED))
582		    != PAM_SUCCESS) {
583			syslog(LOG_ERR, "pam_setcred: %s",
584			    pam_strerror(pamh, e));
585		}
586
587	        /*
588	         * Add any environmental variables that the
589	         * PAM modules may have set.
590		 * Call *after* opening session!
591		 */
592		if (pamh) {
593		  environ_pam = pam_getenvlist(pamh);
594		  if (environ_pam)
595			export_pam_environment();
596		}
597
598		/*
599		 * We must fork() before setuid() because we need to call
600		 * pam_close_session() as root.
601		 */
602		pid = fork();
603		if (pid < 0) {
604			err(1, "fork");
605			PAM_END;
606			exit(0);
607		} else if (pid) {
608			/* parent - wait for child to finish, then cleanup
609			   session */
610			wait(NULL);
611			PAM_END;
612			exit(0);
613		} else {
614			if ((e = pam_end(pamh, PAM_DATA_SILENT)) != PAM_SUCCESS)
615				syslog(LOG_ERR, "pam_end: %s",
616				    pam_strerror(pamh, e));
617		}
618	}
619
620	/*
621	 * We don't need to be root anymore, so
622	 * set the user and session context
623	 */
624	if (setlogin(username) != 0) {
625                syslog(LOG_ERR, "setlogin(%s): %m - exiting", username);
626		exit(1);
627	}
628	if (setusercontext(lc, pwd, pwd->pw_uid,
629	    LOGIN_SETALL & ~(LOGIN_SETLOGIN|LOGIN_SETGROUP)) != 0) {
630                syslog(LOG_ERR, "setusercontext() failed - exiting");
631		exit(1);
632	}
633
634	(void)setenv("SHELL", pwd->pw_shell, 1);
635	(void)setenv("HOME", pwd->pw_dir, 1);
636	if (term != NULL && *term != '\0')
637		(void)setenv("TERM", term, 1);		/* Preset overrides */
638	else {
639		(void)setenv("TERM", stypeof(tty), 0);	/* Fallback doesn't */
640	}
641	(void)setenv("LOGNAME", username, 1);
642	(void)setenv("USER", username, 1);
643	(void)setenv("PATH", rootlogin ? _PATH_STDPATH : _PATH_DEFPATH, 0);
644
645	if (!quietlog) {
646		char	*cw;
647
648		cw = login_getcapstr(lc, "copyright", NULL, NULL);
649		if (cw != NULL && access(cw, F_OK) == 0)
650			motd(cw);
651		else
652		    (void)printf("%s\n\t%s %s\n",
653	"Copyright (c) 1980, 1983, 1986, 1988, 1990, 1991, 1993, 1994",
654	"The Regents of the University of California. ",
655	"All rights reserved.");
656
657		(void)printf("\n");
658
659		cw = login_getcapstr(lc, "welcome", NULL, NULL);
660		if (cw == NULL || access(cw, F_OK) != 0)
661			cw = _PATH_MOTDFILE;
662		motd(cw);
663
664		if (login_getcapbool(lc, "nocheckmail", 0) == 0) {
665			/* $MAIL may have been set by class. */
666			cw = getenv("MAIL");
667			if (cw != NULL)
668				strlcpy(tbuf, cw, sizeof(tbuf));
669			else
670				snprintf(tbuf, sizeof(tbuf), "%s/%s",
671				    _PATH_MAILDIR, pwd->pw_name);
672			if (stat(tbuf, &st) == 0 && st.st_size != 0)
673				(void)printf("You have %smail.\n",
674				    (st.st_mtime > st.st_atime) ? "new " : "");
675		}
676	}
677
678	login_close(lc);
679
680	(void)signal(SIGALRM, SIG_DFL);
681	(void)signal(SIGQUIT, SIG_DFL);
682	(void)signal(SIGINT, SIG_DFL);
683	(void)signal(SIGTSTP, SIG_IGN);
684
685	/*
686	 * Login shells have a leading '-' in front of argv[0]
687	 */
688	if (snprintf(tbuf, sizeof(tbuf), "-%s",
689	    (p = strrchr(pwd->pw_shell, '/')) ? p + 1 : pwd->pw_shell) >=
690	    sizeof(tbuf)) {
691		syslog(LOG_ERR, "user: %s: shell exceeds maximum pathname size",
692		    username);
693		errx(1, "shell exceeds maximum pathname size");
694	}
695
696	execlp(shell, tbuf, (char *)0);
697	err(1, "%s", shell);
698}
699
700static int
701auth_traditional()
702{
703	int rval;
704	char *p;
705	char *ep;
706	char *salt;
707
708	rval = 1;
709	salt = pwd != NULL ? pwd->pw_passwd : "xx";
710
711	p = getpass(passwd_prompt);
712	ep = crypt(p, salt);
713
714	if (pwd) {
715		if (!p[0] && pwd->pw_passwd[0])
716			ep = ":";
717		if (strcmp(ep, pwd->pw_passwd) == 0)
718			rval = 0;
719	}
720
721	/* clear entered password */
722	memset(p, 0, strlen(p));
723	return rval;
724}
725
726/*
727 * Attempt to authenticate the user using PAM.  Returns 0 if the user is
728 * authenticated, or 1 if not authenticated.  If some sort of PAM system
729 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
730 * function returns -1.  This can be used as an indication that we should
731 * fall back to a different authentication mechanism.
732 */
733static int
734auth_pam()
735{
736	const char *tmpl_user;
737	const void *item;
738	int rval;
739	int e;
740	static struct pam_conv conv = { misc_conv, NULL };
741
742	if ((e = pam_start("login", username, &conv, &pamh)) != PAM_SUCCESS) {
743		syslog(LOG_ERR, "pam_start: %s", pam_strerror(pamh, e));
744		return -1;
745	}
746	if ((e = pam_set_item(pamh, PAM_TTY, tty)) != PAM_SUCCESS) {
747		syslog(LOG_ERR, "pam_set_item(PAM_TTY): %s",
748		    pam_strerror(pamh, e));
749		return -1;
750	}
751	if (hostname != NULL &&
752	    (e = pam_set_item(pamh, PAM_RHOST, full_hostname)) != PAM_SUCCESS) {
753		syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
754		    pam_strerror(pamh, e));
755		return -1;
756	}
757	e = pam_authenticate(pamh, 0);
758	switch (e) {
759
760	case PAM_SUCCESS:
761		/*
762		 * With PAM we support the concept of a "template"
763		 * user.  The user enters a login name which is
764		 * authenticated by PAM, usually via a remote service
765		 * such as RADIUS or TACACS+.  If authentication
766		 * succeeds, a different but related "template" name
767		 * is used for setting the credentials, shell, and
768		 * home directory.  The name the user enters need only
769		 * exist on the remote authentication server, but the
770		 * template name must be present in the local password
771		 * database.
772		 *
773		 * This is supported by two various mechanisms in the
774		 * individual modules.  However, from the application's
775		 * point of view, the template user is always passed
776		 * back as a changed value of the PAM_USER item.
777		 */
778		if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
779		    PAM_SUCCESS) {
780			tmpl_user = (const char *) item;
781			if (strcmp(username, tmpl_user) != 0)
782				pwd = getpwnam(tmpl_user);
783		} else
784			syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
785			    pam_strerror(pamh, e));
786		rval = 0;
787		break;
788
789	case PAM_AUTH_ERR:
790	case PAM_USER_UNKNOWN:
791	case PAM_MAXTRIES:
792		rval = 1;
793		break;
794
795	default:
796		syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
797		rval = -1;
798		break;
799	}
800
801	if (rval == 0) {
802		e = pam_acct_mgmt(pamh, 0);
803		if (e == PAM_NEW_AUTHTOK_REQD) {
804			e = pam_chauthtok(pamh, PAM_CHANGE_EXPIRED_AUTHTOK);
805			if (e != PAM_SUCCESS) {
806				syslog(LOG_ERR, "pam_chauthtok: %s",
807				    pam_strerror(pamh, e));
808				rval = 1;
809			}
810		} else if (e != PAM_SUCCESS) {
811			rval = 1;
812		}
813	}
814
815	if (rval != 0) {
816		if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
817			syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
818		}
819		pamh = NULL;
820	}
821	return rval;
822}
823
824static int
825export_pam_environment()
826{
827	char	**pp;
828
829	for (pp = environ_pam; *pp != NULL; pp++) {
830		if (ok_to_export(*pp))
831			(void) putenv(*pp);
832		free(*pp);
833	}
834	return PAM_SUCCESS;
835}
836
837/*
838 * Sanity checks on PAM environmental variables:
839 * - Make sure there is an '=' in the string.
840 * - Make sure the string doesn't run on too long.
841 * - Do not export certain variables.  This list was taken from the
842 *   Solaris pam_putenv(3) man page.
843 */
844static int
845ok_to_export(s)
846	const char *s;
847{
848	static const char *noexport[] = {
849		"SHELL", "HOME", "LOGNAME", "MAIL", "CDPATH",
850		"IFS", "PATH", NULL
851	};
852	const char **pp;
853	size_t n;
854
855	if (strlen(s) > 1024 || strchr(s, '=') == NULL)
856		return 0;
857	if (strncmp(s, "LD_", 3) == 0)
858		return 0;
859	for (pp = noexport; *pp != NULL; pp++) {
860		n = strlen(*pp);
861		if (s[n] == '=' && strncmp(s, *pp, n) == 0)
862			return 0;
863	}
864	return 1;
865}
866
867static void
868usage()
869{
870
871	(void)fprintf(stderr, "usage: login [-fp] [-h hostname] [username]\n");
872	exit(1);
873}
874
875/*
876 * Allow for authentication style and/or kerberos instance
877 */
878
879#define	NBUFSIZ		UT_NAMESIZE + 64
880
881void
882getloginname()
883{
884	int ch;
885	char *p;
886	static char nbuf[NBUFSIZ];
887
888	for (;;) {
889		(void)printf("%s", prompt);
890		for (p = nbuf; (ch = getchar()) != '\n'; ) {
891			if (ch == EOF) {
892				badlogin(username);
893				exit(0);
894			}
895			if (p < nbuf + (NBUFSIZ - 1))
896				*p++ = ch;
897		}
898		if (p > nbuf) {
899			if (nbuf[0] == '-')
900				(void)fprintf(stderr,
901				    "login names may not start with '-'.\n");
902			else {
903				*p = '\0';
904				username = nbuf;
905				break;
906			}
907		}
908	}
909}
910
911int
912rootterm(ttyn)
913	char *ttyn;
914{
915	struct ttyent *t;
916
917	return ((t = getttynam(ttyn)) && t->ty_status & TTY_SECURE);
918}
919
920volatile int motdinterrupt;
921
922void
923sigint(signo)
924	int signo __unused;
925{
926	motdinterrupt = 1;
927}
928
929void
930motd(motdfile)
931	char *motdfile;
932{
933	int fd, nchars;
934	sig_t oldint;
935	char tbuf[256];
936
937	if ((fd = open(motdfile, O_RDONLY, 0)) < 0)
938		return;
939	motdinterrupt = 0;
940	oldint = signal(SIGINT, sigint);
941	while ((nchars = read(fd, tbuf, sizeof(tbuf))) > 0 && !motdinterrupt)
942		(void)write(fileno(stdout), tbuf, nchars);
943	(void)signal(SIGINT, oldint);
944	(void)close(fd);
945}
946
947/* ARGSUSED */
948void
949timedout(signo)
950	int signo;
951{
952
953	longjmp(timeout_buf, signo);
954}
955
956
957void
958dolastlog(quiet)
959	int quiet;
960{
961	struct lastlog ll;
962	int fd;
963
964	if ((fd = open(_PATH_LASTLOG, O_RDWR, 0)) >= 0) {
965		(void)lseek(fd, (off_t)pwd->pw_uid * sizeof(ll), L_SET);
966		if (!quiet) {
967			if (read(fd, (char *)&ll, sizeof(ll)) == sizeof(ll) &&
968			    ll.ll_time != 0) {
969				(void)printf("Last login: %.*s ",
970				    24-5, (char *)ctime(&ll.ll_time));
971				if (*ll.ll_host != '\0')
972					(void)printf("from %.*s\n",
973					    (int)sizeof(ll.ll_host),
974					    ll.ll_host);
975				else
976					(void)printf("on %.*s\n",
977					    (int)sizeof(ll.ll_line),
978					    ll.ll_line);
979			}
980			(void)lseek(fd, (off_t)pwd->pw_uid * sizeof(ll), L_SET);
981		}
982		memset((void *)&ll, 0, sizeof(ll));
983		(void)time(&ll.ll_time);
984		(void)strncpy(ll.ll_line, tty, sizeof(ll.ll_line));
985		if (hostname)
986			(void)strncpy(ll.ll_host, hostname, sizeof(ll.ll_host));
987		(void)write(fd, (char *)&ll, sizeof(ll));
988		(void)close(fd);
989	} else {
990		syslog(LOG_ERR, "cannot open %s: %m", _PATH_LASTLOG);
991	}
992}
993
994void
995badlogin(name)
996	char *name;
997{
998
999	if (failures == 0)
1000		return;
1001	if (hostname) {
1002		syslog(LOG_NOTICE, "%d LOGIN FAILURE%s FROM %s",
1003		    failures, failures > 1 ? "S" : "", full_hostname);
1004		syslog(LOG_AUTHPRIV|LOG_NOTICE,
1005		    "%d LOGIN FAILURE%s FROM %s, %s",
1006		    failures, failures > 1 ? "S" : "", full_hostname, name);
1007	} else {
1008		syslog(LOG_NOTICE, "%d LOGIN FAILURE%s ON %s",
1009		    failures, failures > 1 ? "S" : "", tty);
1010		syslog(LOG_AUTHPRIV|LOG_NOTICE,
1011		    "%d LOGIN FAILURE%s ON %s, %s",
1012		    failures, failures > 1 ? "S" : "", tty, name);
1013	}
1014	failures = 0;
1015}
1016
1017#undef	UNKNOWN
1018#define	UNKNOWN	"su"
1019
1020char *
1021stypeof(ttyid)
1022	char *ttyid;
1023{
1024	struct ttyent *t;
1025
1026	if (ttyid != NULL && *ttyid != '\0') {
1027		t = getttynam(ttyid);
1028		if (t != NULL && t->ty_type != NULL)
1029			return (t->ty_type);
1030	}
1031	return (UNKNOWN);
1032}
1033
1034void
1035refused(msg, rtype, lout)
1036	char *msg;
1037	char *rtype;
1038	int lout;
1039{
1040
1041	if (msg != NULL)
1042	    printf("%s.\n", msg);
1043	if (hostname)
1044		syslog(LOG_NOTICE, "LOGIN %s REFUSED (%s) FROM %s ON TTY %s",
1045		    pwd->pw_name, rtype, full_hostname, tty);
1046	else
1047		syslog(LOG_NOTICE, "LOGIN %s REFUSED (%s) ON TTY %s",
1048		    pwd->pw_name, rtype, tty);
1049	if (lout)
1050		sleepexit(1);
1051}
1052
1053void
1054sleepexit(eval)
1055	int eval;
1056{
1057
1058	(void)sleep(5);
1059	exit(eval);
1060}
1061