login.c revision 83519
1226048Sobrien/*-
2133359Sobrien * Copyright (c) 1980, 1987, 1988, 1991, 1993, 1994
3267843Sdelphij *	The Regents of the University of California.  All rights reserved.
4133359Sobrien *
5133359Sobrien * Redistribution and use in source and binary forms, with or without
6133359Sobrien * modification, are permitted provided that the following conditions
7169962Sobrien * are met:
8133359Sobrien * 1. Redistributions of source code must retain the above copyright
9133359Sobrien *    notice, this list of conditions and the following disclaimer.
10133359Sobrien * 2. Redistributions in binary form must reproduce the above copyright
11133359Sobrien *    notice, this list of conditions and the following disclaimer in the
12133359Sobrien *    documentation and/or other materials provided with the distribution.
13133359Sobrien * 3. All advertising materials mentioning features or use of this software
14133359Sobrien *    must display the following acknowledgement:
15133359Sobrien *	This product includes software developed by the University of
16186690Sobrien *	California, Berkeley and its contributors.
17133359Sobrien * 4. Neither the name of the University nor the names of its contributors
18133359Sobrien *    may be used to endorse or promote products derived from this software
19133359Sobrien *    without specific prior written permission.
20133359Sobrien *
21133359Sobrien * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22133359Sobrien * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23133359Sobrien * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24133359Sobrien * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25133359Sobrien * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26133359Sobrien * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27133359Sobrien * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28133359Sobrien * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29133359Sobrien * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30133359Sobrien * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31133359Sobrien * SUCH DAMAGE.
32133359Sobrien */
33133359Sobrien
34133359Sobrien#if 0
35133359Sobrienstatic char copyright[] =
36133359Sobrien"@(#) Copyright (c) 1980, 1987, 1988, 1991, 1993, 1994\n\
37133359Sobrien	The Regents of the University of California.  All rights reserved.\n";
38133359Sobrien#endif
39133359Sobrien
40133359Sobrien#ifndef lint
41133359Sobrien#if 0
42133359Sobrienstatic char sccsid[] = "@(#)login.c	8.4 (Berkeley) 4/2/94";
43133359Sobrien#endif
44133359Sobrienstatic const char rcsid[] =
45133359Sobrien  "$FreeBSD: head/usr.bin/login/login.c 83519 2001-09-15 17:09:39Z rwatson $";
46133359Sobrien#endif /* not lint */
47133359Sobrien
48133359Sobrien/*
49133359Sobrien * login [ name ]
50133359Sobrien * login -h hostname	(for telnetd, etc.)
51133359Sobrien * login -f name	(for pre-authenticated login: datakit, xterm, etc.)
52133359Sobrien */
53133359Sobrien
54133359Sobrien#include <sys/copyright.h>
55133359Sobrien#include <sys/param.h>
56133359Sobrien#include <sys/stat.h>
57133359Sobrien#include <sys/socket.h>
58133359Sobrien#include <sys/time.h>
59133359Sobrien#include <sys/resource.h>
60133359Sobrien#include <sys/file.h>
61133359Sobrien#include <netinet/in.h>
62133359Sobrien#include <arpa/inet.h>
63133359Sobrien
64133359Sobrien#include <err.h>
65133359Sobrien#include <errno.h>
66133359Sobrien#include <grp.h>
67133359Sobrien#include <libutil.h>
68133359Sobrien#include <login_cap.h>
69133359Sobrien#include <netdb.h>
70133359Sobrien#include <pwd.h>
71133359Sobrien#include <setjmp.h>
72133359Sobrien#include <signal.h>
73133359Sobrien#include <stdio.h>
74133359Sobrien#include <stdlib.h>
75133359Sobrien#include <string.h>
76133359Sobrien#include <syslog.h>
77133359Sobrien#include <ttyent.h>
78133359Sobrien#include <unistd.h>
79133359Sobrien#include <utmp.h>
80133359Sobrien
81133359Sobrien#include <security/pam_appl.h>
82133359Sobrien#include <security/pam_misc.h>
83133359Sobrien#include <sys/wait.h>
84133359Sobrien
85133359Sobrien#include "pathnames.h"
86133359Sobrien
87133359Sobrien/* wrapper for KAME-special getnameinfo() */
88133359Sobrien#ifndef NI_WITHSCOPEID
89133359Sobrien#define	NI_WITHSCOPEID	0
90133359Sobrien#endif
91133359Sobrien
92133359Sobrienvoid	 badlogin __P((char *));
93133359Sobrienvoid	 dolastlog __P((int));
94133359Sobrienvoid	 getloginname __P((void));
95133359Sobrienvoid	 motd __P((char *));
96133359Sobrienint	 rootterm __P((char *));
97133359Sobrienvoid	 sigint __P((int));
98133359Sobrienvoid	 sleepexit __P((int));
99133359Sobrienvoid	 refused __P((char *,char *,int));
100133359Sobrienchar	*stypeof __P((char *));
101133359Sobrienvoid	 timedout __P((int));
102133359Sobrienint	 login_access __P((char *, char *));
103133359Sobrienvoid     login_fbtab __P((char *, uid_t, gid_t));
104133359Sobrien
105133359Sobrienstatic int auth_pam __P((void));
106133359Sobrienstatic int export_pam_environment __P((void));
107133359Sobrienstatic int ok_to_export __P((const char *));
108169942Sobrien
109169942Sobrienstatic pam_handle_t *pamh = NULL;
110169942Sobrienstatic char **environ_pam;
111186690Sobrien
112133359Sobrien#define PAM_END { \
113267843Sdelphij	if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS) \
114133359Sobrien		syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e)); \
115133359Sobrien	if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS) \
116159764Sobrien		syslog(LOG_ERR, "pam_close_session: %s", pam_strerror(pamh, e)); \
117159764Sobrien	if ((e = pam_end(pamh, e)) != PAM_SUCCESS) \
118159764Sobrien		syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e)); \
119159764Sobrien}
120159764Sobrien
121159764Sobrienstatic int auth_traditional __P((void));
122169942Sobrienextern void login __P((struct utmp *));
123169942Sobrienstatic void usage __P((void));
124169942Sobrien
125169942Sobrien#define	TTYGRPNAME	"tty"		/* name of group to own ttys */
126169942Sobrien#define	DEFAULT_BACKOFF	3
127186690Sobrien#define	DEFAULT_RETRIES	10
128169942Sobrien#define	DEFAULT_PROMPT		"login: "
129169942Sobrien#define	DEFAULT_PASSWD_PROMPT	"Password:"
130169942Sobrien
131169942Sobrien/*
132169942Sobrien * This bounds the time given to login.  Not a define so it can
133169942Sobrien * be patched on machines where it's too small.
134186690Sobrien */
135186690Sobrienu_int	timeout = 300;
136186690Sobrien
137186690Sobrien/* Buffer for signal handling of timeout */
138186690Sobrienjmp_buf timeout_buf;
139186690Sobrien
140186690Sobrienstruct	passwd *pwd;
141186690Sobrienint	failures;
142186690Sobrienchar	*term, *envinit[1], *hostname, *passwd_prompt, *prompt, *tty, *username;
143186690Sobrienchar    full_hostname[MAXHOSTNAMELEN];
144186690Sobrien
145186690Sobrienint
146186690Sobrienmain(argc, argv)
147186690Sobrien	int argc;
148186690Sobrien	char *argv[];
149186690Sobrien{
150186690Sobrien	extern char **environ;
151186690Sobrien	struct group *gr;
152186690Sobrien	struct stat st;
153226048Sobrien	struct timeval tp;
154226048Sobrien	struct utmp utmp;
155226048Sobrien	int rootok, retries, backoff;
156226048Sobrien	int ask, ch, cnt, fflag, hflag, pflag, quietlog, rootlogin, rval;
157226048Sobrien	time_t warntime;
158226048Sobrien	uid_t uid, euid;
159267843Sdelphij	gid_t egid;
160267843Sdelphij	char *p, *ttyn;
161267843Sdelphij	char tbuf[MAXPATHLEN + 2];
162267843Sdelphij	char tname[sizeof(_PATH_TTY) + 10];
163267843Sdelphij	char *shell = NULL;
164226048Sobrien	login_cap_t *lc = NULL;
165226048Sobrien	pid_t pid;
166226048Sobrien	int e;
167226048Sobrien
168226048Sobrien	(void)signal(SIGQUIT, SIG_IGN);
169267843Sdelphij	(void)signal(SIGINT, SIG_IGN);
170267843Sdelphij	(void)signal(SIGHUP, SIG_IGN);
171267843Sdelphij	if (setjmp(timeout_buf)) {
172267843Sdelphij		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		cw = getenv("MAIL");	/* $MAIL may have been set by class */
665		if (cw != NULL)
666			strlcpy(tbuf, cw, sizeof(tbuf));
667		else
668			snprintf(tbuf, sizeof(tbuf), "%s/%s", _PATH_MAILDIR,
669			    pwd->pw_name);
670		if (stat(tbuf, &st) == 0 && st.st_size != 0)
671			(void)printf("You have %smail.\n",
672			    (st.st_mtime > st.st_atime) ? "new " : "");
673	}
674
675	login_close(lc);
676
677	(void)signal(SIGALRM, SIG_DFL);
678	(void)signal(SIGQUIT, SIG_DFL);
679	(void)signal(SIGINT, SIG_DFL);
680	(void)signal(SIGTSTP, SIG_IGN);
681
682	/*
683	 * Login shells have a leading '-' in front of argv[0]
684	 */
685	if (snprintf(tbuf, sizeof(tbuf), "-%s",
686	    (p = strrchr(pwd->pw_shell, '/')) ? p + 1 : pwd->pw_shell) >=
687	    sizeof(tbuf)) {
688		syslog(LOG_ERR, "user: %s: shell exceeds maximum pathname size",
689		    username);
690		errx(1, "shell exceeds maximum pathname size");
691	}
692
693	execlp(shell, tbuf, (char *)0);
694	err(1, "%s", shell);
695}
696
697static int
698auth_traditional()
699{
700	int rval;
701	char *p;
702	char *ep;
703	char *salt;
704
705	rval = 1;
706	salt = pwd != NULL ? pwd->pw_passwd : "xx";
707
708	p = getpass(passwd_prompt);
709	ep = crypt(p, salt);
710
711	if (pwd) {
712		if (!p[0] && pwd->pw_passwd[0])
713			ep = ":";
714		if (strcmp(ep, pwd->pw_passwd) == 0)
715			rval = 0;
716	}
717
718	/* clear entered password */
719	memset(p, 0, strlen(p));
720	return rval;
721}
722
723/*
724 * Attempt to authenticate the user using PAM.  Returns 0 if the user is
725 * authenticated, or 1 if not authenticated.  If some sort of PAM system
726 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
727 * function returns -1.  This can be used as an indication that we should
728 * fall back to a different authentication mechanism.
729 */
730static int
731auth_pam()
732{
733	const char *tmpl_user;
734	const void *item;
735	int rval;
736	int e;
737	static struct pam_conv conv = { misc_conv, NULL };
738
739	if ((e = pam_start("login", username, &conv, &pamh)) != PAM_SUCCESS) {
740		syslog(LOG_ERR, "pam_start: %s", pam_strerror(pamh, e));
741		return -1;
742	}
743	if ((e = pam_set_item(pamh, PAM_TTY, tty)) != PAM_SUCCESS) {
744		syslog(LOG_ERR, "pam_set_item(PAM_TTY): %s",
745		    pam_strerror(pamh, e));
746		return -1;
747	}
748	if (hostname != NULL &&
749	    (e = pam_set_item(pamh, PAM_RHOST, full_hostname)) != PAM_SUCCESS) {
750		syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
751		    pam_strerror(pamh, e));
752		return -1;
753	}
754	e = pam_authenticate(pamh, 0);
755	switch (e) {
756
757	case PAM_SUCCESS:
758		/*
759		 * With PAM we support the concept of a "template"
760		 * user.  The user enters a login name which is
761		 * authenticated by PAM, usually via a remote service
762		 * such as RADIUS or TACACS+.  If authentication
763		 * succeeds, a different but related "template" name
764		 * is used for setting the credentials, shell, and
765		 * home directory.  The name the user enters need only
766		 * exist on the remote authentication server, but the
767		 * template name must be present in the local password
768		 * database.
769		 *
770		 * This is supported by two various mechanisms in the
771		 * individual modules.  However, from the application's
772		 * point of view, the template user is always passed
773		 * back as a changed value of the PAM_USER item.
774		 */
775		if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
776		    PAM_SUCCESS) {
777			tmpl_user = (const char *) item;
778			if (strcmp(username, tmpl_user) != 0)
779				pwd = getpwnam(tmpl_user);
780		} else
781			syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
782			    pam_strerror(pamh, e));
783		rval = 0;
784		break;
785
786	case PAM_AUTH_ERR:
787	case PAM_USER_UNKNOWN:
788	case PAM_MAXTRIES:
789		rval = 1;
790		break;
791
792	default:
793		syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
794		rval = -1;
795		break;
796	}
797
798	if (rval == 0) {
799		e = pam_acct_mgmt(pamh, 0);
800		if (e == PAM_NEW_AUTHTOK_REQD) {
801			e = pam_chauthtok(pamh, PAM_CHANGE_EXPIRED_AUTHTOK);
802			if (e != PAM_SUCCESS) {
803				syslog(LOG_ERR, "pam_chauthtok: %s",
804				    pam_strerror(pamh, e));
805				rval = 1;
806			}
807		} else if (e != PAM_SUCCESS) {
808			rval = 1;
809		}
810	}
811
812	if (rval != 0) {
813		if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
814			syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
815		}
816		pamh = NULL;
817	}
818	return rval;
819}
820
821static int
822export_pam_environment()
823{
824	char	**pp;
825
826	for (pp = environ_pam; *pp != NULL; pp++) {
827		if (ok_to_export(*pp))
828			(void) putenv(*pp);
829		free(*pp);
830	}
831	return PAM_SUCCESS;
832}
833
834/*
835 * Sanity checks on PAM environmental variables:
836 * - Make sure there is an '=' in the string.
837 * - Make sure the string doesn't run on too long.
838 * - Do not export certain variables.  This list was taken from the
839 *   Solaris pam_putenv(3) man page.
840 */
841static int
842ok_to_export(s)
843	const char *s;
844{
845	static const char *noexport[] = {
846		"SHELL", "HOME", "LOGNAME", "MAIL", "CDPATH",
847		"IFS", "PATH", NULL
848	};
849	const char **pp;
850	size_t n;
851
852	if (strlen(s) > 1024 || strchr(s, '=') == NULL)
853		return 0;
854	if (strncmp(s, "LD_", 3) == 0)
855		return 0;
856	for (pp = noexport; *pp != NULL; pp++) {
857		n = strlen(*pp);
858		if (s[n] == '=' && strncmp(s, *pp, n) == 0)
859			return 0;
860	}
861	return 1;
862}
863
864static void
865usage()
866{
867
868	(void)fprintf(stderr, "usage: login [-fp] [-h hostname] [username]\n");
869	exit(1);
870}
871
872/*
873 * Allow for authentication style and/or kerberos instance
874 */
875
876#define	NBUFSIZ		UT_NAMESIZE + 64
877
878void
879getloginname()
880{
881	int ch;
882	char *p;
883	static char nbuf[NBUFSIZ];
884
885	for (;;) {
886		(void)printf("%s", prompt);
887		for (p = nbuf; (ch = getchar()) != '\n'; ) {
888			if (ch == EOF) {
889				badlogin(username);
890				exit(0);
891			}
892			if (p < nbuf + (NBUFSIZ - 1))
893				*p++ = ch;
894		}
895		if (p > nbuf) {
896			if (nbuf[0] == '-')
897				(void)fprintf(stderr,
898				    "login names may not start with '-'.\n");
899			else {
900				*p = '\0';
901				username = nbuf;
902				break;
903			}
904		}
905	}
906}
907
908int
909rootterm(ttyn)
910	char *ttyn;
911{
912	struct ttyent *t;
913
914	return ((t = getttynam(ttyn)) && t->ty_status & TTY_SECURE);
915}
916
917volatile int motdinterrupt;
918
919void
920sigint(signo)
921	int signo __unused;
922{
923	motdinterrupt = 1;
924}
925
926void
927motd(motdfile)
928	char *motdfile;
929{
930	int fd, nchars;
931	sig_t oldint;
932	char tbuf[256];
933
934	if ((fd = open(motdfile, O_RDONLY, 0)) < 0)
935		return;
936	motdinterrupt = 0;
937	oldint = signal(SIGINT, sigint);
938	while ((nchars = read(fd, tbuf, sizeof(tbuf))) > 0 && !motdinterrupt)
939		(void)write(fileno(stdout), tbuf, nchars);
940	(void)signal(SIGINT, oldint);
941	(void)close(fd);
942}
943
944/* ARGSUSED */
945void
946timedout(signo)
947	int signo;
948{
949
950	longjmp(timeout_buf, signo);
951}
952
953
954void
955dolastlog(quiet)
956	int quiet;
957{
958	struct lastlog ll;
959	int fd;
960
961	if ((fd = open(_PATH_LASTLOG, O_RDWR, 0)) >= 0) {
962		(void)lseek(fd, (off_t)pwd->pw_uid * sizeof(ll), L_SET);
963		if (!quiet) {
964			if (read(fd, (char *)&ll, sizeof(ll)) == sizeof(ll) &&
965			    ll.ll_time != 0) {
966				(void)printf("Last login: %.*s ",
967				    24-5, (char *)ctime(&ll.ll_time));
968				if (*ll.ll_host != '\0')
969					(void)printf("from %.*s\n",
970					    (int)sizeof(ll.ll_host),
971					    ll.ll_host);
972				else
973					(void)printf("on %.*s\n",
974					    (int)sizeof(ll.ll_line),
975					    ll.ll_line);
976			}
977			(void)lseek(fd, (off_t)pwd->pw_uid * sizeof(ll), L_SET);
978		}
979		memset((void *)&ll, 0, sizeof(ll));
980		(void)time(&ll.ll_time);
981		(void)strncpy(ll.ll_line, tty, sizeof(ll.ll_line));
982		if (hostname)
983			(void)strncpy(ll.ll_host, hostname, sizeof(ll.ll_host));
984		(void)write(fd, (char *)&ll, sizeof(ll));
985		(void)close(fd);
986	} else {
987		syslog(LOG_ERR, "cannot open %s: %m", _PATH_LASTLOG);
988	}
989}
990
991void
992badlogin(name)
993	char *name;
994{
995
996	if (failures == 0)
997		return;
998	if (hostname) {
999		syslog(LOG_NOTICE, "%d LOGIN FAILURE%s FROM %s",
1000		    failures, failures > 1 ? "S" : "", full_hostname);
1001		syslog(LOG_AUTHPRIV|LOG_NOTICE,
1002		    "%d LOGIN FAILURE%s FROM %s, %s",
1003		    failures, failures > 1 ? "S" : "", full_hostname, name);
1004	} else {
1005		syslog(LOG_NOTICE, "%d LOGIN FAILURE%s ON %s",
1006		    failures, failures > 1 ? "S" : "", tty);
1007		syslog(LOG_AUTHPRIV|LOG_NOTICE,
1008		    "%d LOGIN FAILURE%s ON %s, %s",
1009		    failures, failures > 1 ? "S" : "", tty, name);
1010	}
1011	failures = 0;
1012}
1013
1014#undef	UNKNOWN
1015#define	UNKNOWN	"su"
1016
1017char *
1018stypeof(ttyid)
1019	char *ttyid;
1020{
1021	struct ttyent *t;
1022
1023	if (ttyid != NULL && *ttyid != '\0') {
1024		t = getttynam(ttyid);
1025		if (t != NULL && t->ty_type != NULL)
1026			return (t->ty_type);
1027	}
1028	return (UNKNOWN);
1029}
1030
1031void
1032refused(msg, rtype, lout)
1033	char *msg;
1034	char *rtype;
1035	int lout;
1036{
1037
1038	if (msg != NULL)
1039	    printf("%s.\n", msg);
1040	if (hostname)
1041		syslog(LOG_NOTICE, "LOGIN %s REFUSED (%s) FROM %s ON TTY %s",
1042		    pwd->pw_name, rtype, full_hostname, tty);
1043	else
1044		syslog(LOG_NOTICE, "LOGIN %s REFUSED (%s) ON TTY %s",
1045		    pwd->pw_name, rtype, tty);
1046	if (lout)
1047		sleepexit(1);
1048}
1049
1050void
1051sleepexit(eval)
1052	int eval;
1053{
1054
1055	(void)sleep(5);
1056	exit(eval);
1057}
1058