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