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