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