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