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