kernel: Remove the FFS_ROOT option. It was a no-op since 4.9.
[dragonfly.git] / usr.bin / login / login.c
blob2ecf77f1d36e1b286dfa64c3d6b0d73ea4aa087b
1 /*-
2 * Copyright (c) 1980, 1987, 1988, 1991, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
4 * Copyright (c) 2002 Networks Associates Technologies, Inc.
5 * All rights reserved.
7 * Portions of this software were developed for the FreeBSD Project by
8 * ThinkSec AS and NAI Labs, the Security Research Division of Network
9 * Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035
10 * ("CBOSS"), as part of the DARPA CHATS research program.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
36 * @(#)login.c 8.4 (Berkeley) 4/2/94
37 * $FreeBSD: src/usr.bin/login/login.c,v 1.106 2007/07/04 00:00:40 scf Exp $
41 * login [ name ]
42 * login -h hostname (for telnetd, etc.)
43 * login -f name (for pre-authenticated login: datakit, xterm, etc.)
46 #include <sys/copyright.h>
47 #include <sys/param.h>
48 #include <sys/file.h>
49 #include <sys/stat.h>
50 #include <sys/time.h>
51 #include <sys/resource.h>
52 #include <sys/wait.h>
54 #include <err.h>
55 #include <errno.h>
56 #include <grp.h>
57 #include <libutil.h>
58 #include <login_cap.h>
59 #include <pwd.h>
60 #include <setjmp.h>
61 #include <signal.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <string.h>
65 #include <syslog.h>
66 #include <ttyent.h>
67 #include <unistd.h>
69 #include <security/pam_appl.h>
70 #include <security/openpam.h>
72 #include "login.h"
73 #include "pathnames.h"
75 static int auth_pam(void);
76 static void bail(int, int);
77 static int export(const char *);
78 static void export_pam_environment(void);
79 static int motd(const char *);
80 static void badlogin(char *);
81 static char *getloginname(void);
82 static void pam_syslog(const char *);
83 static void pam_cleanup(void);
84 static void refused(const char *, const char *, int);
85 static const char *stypeof(char *);
86 static void sigint(int);
87 static void timedout(int);
88 static void usage(void);
90 #define TTYGRPNAME "tty" /* group to own ttys */
91 #define DEFAULT_BACKOFF 3
92 #define DEFAULT_RETRIES 10
93 #define DEFAULT_PROMPT "login: "
94 #define DEFAULT_PASSWD_PROMPT "Password:"
95 #define TERM_UNKNOWN "su"
96 #define DEFAULT_WARN (2L * 7L * 86400L) /* Two weeks */
97 #define NO_SLEEP_EXIT 0
98 #define SLEEP_EXIT 5
101 * This bounds the time given to login. Not a define so it can
102 * be patched on machines where it's too small.
104 static u_int timeout = 300;
106 /* Buffer for signal handling of timeout */
107 static jmp_buf timeout_buf;
109 struct passwd *pwd;
110 static int failures;
112 static char *envinit[1]; /* empty environment list */
115 * Command line flags and arguments
117 static int fflag; /* -f: do not perform authentication */
118 static int hflag; /* -h: login from remote host */
119 static char *hostname; /* hostname from command line */
120 static int pflag; /* -p: preserve environment */
123 * User name
125 static char *username; /* user name */
126 static char *olduser; /* previous user name */
129 * Prompts
131 static char default_prompt[] = DEFAULT_PROMPT;
132 static const char *prompt;
133 static char default_passwd_prompt[] = DEFAULT_PASSWD_PROMPT;
134 static const char *passwd_prompt;
136 static char *tty;
139 * PAM data
141 static pam_handle_t *pamh = NULL;
142 static struct pam_conv pamc = { openpam_ttyconv, NULL };
143 static int pam_err;
144 static int pam_silent = PAM_SILENT;
145 static int pam_cred_established;
146 static int pam_session_established;
149 main(int argc, char **argv)
151 struct group *gr;
152 struct stat st;
153 int retries, backoff;
154 int ask, ch, cnt, quietlog, rootlogin, rval;
155 uid_t uid, euid;
156 gid_t egid;
157 char *term;
158 char *p, *ttyn;
159 char tname[sizeof(_PATH_TTY) + 10];
160 char *arg0;
161 const char *tp;
162 const char *shell = NULL;
163 login_cap_t *lc = NULL;
164 login_cap_t *lc_user = NULL;
165 pid_t pid;
166 #ifdef USE_BSM_AUDIT
167 char auditsuccess = 1;
168 #endif
170 signal(SIGQUIT, SIG_IGN);
171 signal(SIGINT, SIG_IGN);
172 signal(SIGHUP, SIG_IGN);
173 if (setjmp(timeout_buf)) {
174 if (failures)
175 badlogin(username);
176 fprintf(stderr, "Login timed out after %d seconds\n",
177 timeout);
178 bail(NO_SLEEP_EXIT, 0);
180 signal(SIGALRM, timedout);
181 alarm(timeout);
182 setpriority(PRIO_PROCESS, 0, 0);
184 openlog("login", 0, LOG_AUTH);
186 uid = getuid();
187 euid = geteuid();
188 egid = getegid();
190 while ((ch = getopt(argc, argv, "fh:p")) != -1)
191 switch (ch) {
192 case 'f':
193 fflag = 1;
194 break;
195 case 'h':
196 if (uid != 0)
197 errx(1, "-h option: %s", strerror(EPERM));
198 if (strlen(optarg) >= MAXHOSTNAMELEN)
199 errx(1, "-h option: %s: exceeds maximum "
200 "hostname size", optarg);
201 hflag = 1;
202 hostname = optarg;
203 break;
204 case 'p':
205 pflag = 1;
206 break;
207 case '?':
208 default:
209 if (uid == 0)
210 syslog(LOG_ERR, "invalid flag %c", ch);
211 usage();
213 argc -= optind;
214 argv += optind;
216 if (argc > 0) {
217 username = strdup(*argv);
218 if (username == NULL)
219 err(1, "strdup()");
220 ask = 0;
221 } else {
222 ask = 1;
225 setproctitle("-%s", getprogname());
227 for (cnt = getdtablesize(); cnt > 2; cnt--)
228 close(cnt);
231 * Get current TTY
233 ttyn = ttyname(STDIN_FILENO);
234 if (ttyn == NULL || *ttyn == '\0') {
235 snprintf(tname, sizeof(tname), "%s??", _PATH_TTY);
236 ttyn = tname;
238 if (strncmp(ttyn, _PATH_DEV, sizeof(_PATH_DEV) -1) == 0)
239 tty = ttyn + sizeof(_PATH_DEV) -1;
240 else
241 tty = ttyn;
244 * Get "login-retries" & "login-backoff" from default class
246 lc = login_getclass(NULL);
247 prompt = login_getcapstr(lc, "login_prompt",
248 default_prompt, default_prompt);
249 passwd_prompt = login_getcapstr(lc, "passwd_prompt",
250 default_passwd_prompt, default_passwd_prompt);
251 retries = login_getcapnum(lc, "login-retries",
252 DEFAULT_RETRIES, DEFAULT_RETRIES);
253 backoff = login_getcapnum(lc, "login-backoff",
254 DEFAULT_BACKOFF, DEFAULT_BACKOFF);
255 login_close(lc);
256 lc = NULL;
259 * Try to authenticate the user until we succeed or time out.
261 for (cnt = 0;; ask = 1) {
262 if (ask) {
263 fflag = 0;
264 if (olduser != NULL)
265 free(olduser);
266 olduser = username;
267 username = getloginname();
269 rootlogin = 0;
272 * Note if trying multiple user names; log failures for
273 * previous user name, but don't bother logging one failure
274 * for nonexistent name (mistyped username).
276 if (failures && strcmp(olduser, username) != 0) {
277 if (failures > (pwd ? 0 : 1))
278 badlogin(olduser);
282 * Load the PAM policy and set some variables
284 pam_err = pam_start("login", username, &pamc, &pamh);
285 if (pam_err != PAM_SUCCESS) {
286 pam_syslog("pam_start()");
287 #ifdef USE_BSM_AUDIT
288 au_login_fail("PAM Error", 1);
289 #endif
290 bail(NO_SLEEP_EXIT, 1);
292 pam_err = pam_set_item(pamh, PAM_TTY, tty);
293 if (pam_err != PAM_SUCCESS) {
294 pam_syslog("pam_set_item(PAM_TTY)");
295 #ifdef USE_BSM_AUDIT
296 au_login_fail("PAM Error", 1);
297 #endif
298 bail(NO_SLEEP_EXIT, 1);
300 pam_err = pam_set_item(pamh, PAM_RHOST, hostname);
301 if (pam_err != PAM_SUCCESS) {
302 pam_syslog("pam_set_item(PAM_RHOST)");
303 #ifdef USE_BSM_AUDIT
304 au_login_fail("PAM Error", 1);
305 #endif
306 bail(NO_SLEEP_EXIT, 1);
309 pwd = getpwnam(username);
310 if (pwd != NULL && pwd->pw_uid == 0)
311 rootlogin = 1;
314 * If the -f option was specified and the caller is
315 * root or the caller isn't changing their uid, don't
316 * authenticate.
318 if (pwd != NULL && fflag &&
319 (uid == (uid_t)0 || uid == (uid_t)pwd->pw_uid)) {
320 /* already authenticated */
321 rval = 0;
322 #ifdef USE_BSM_AUDIT
323 auditsuccess = 0; /* opened a terminal window only */
324 #endif
325 } else {
326 fflag = 0;
327 setpriority(PRIO_PROCESS, 0, -4);
328 rval = auth_pam();
329 setpriority(PRIO_PROCESS, 0, 0);
332 if (pwd && rval == 0)
333 break;
335 pam_cleanup();
338 * We are not exiting here, but this corresponds to a failed
339 * login event, so set exitstatus to 1.
341 #ifdef USE_BSM_AUDIT
342 au_login_fail("Login incorrect", 1);
343 #endif
345 printf("Login incorrect\n");
346 failures++;
348 pwd = NULL;
351 * Allow up to 'retry' (10) attempts, but start
352 * backing off after 'backoff' (3) attempts.
354 if (++cnt > backoff) {
355 if (cnt >= retries) {
356 badlogin(username);
357 bail(SLEEP_EXIT, 1);
359 sleep((u_int)((cnt - backoff) * 5));
363 /* committed to login -- turn off timeout */
364 alarm((u_int)0);
365 signal(SIGHUP, SIG_DFL);
367 endpwent();
369 #ifdef USE_BSM_AUDIT
370 /* Audit successful login. */
371 if (auditsuccess)
372 au_login_success();
373 #endif
376 * Establish the login class.
378 lc = login_getpwclass(pwd);
379 lc_user = login_getuserclass(pwd);
381 if (!(quietlog = login_getcapbool(lc_user, "hushlogin", 0)))
382 quietlog = login_getcapbool(lc, "hushlogin", 0);
385 * Switching needed for NFS with root access disabled.
387 * XXX: This change fails to modify the additional groups for the
388 * process, and as such, may restrict rights normally granted
389 * through those groups.
391 setegid(pwd->pw_gid);
392 seteuid(rootlogin ? 0 : pwd->pw_uid);
393 if (!*pwd->pw_dir || chdir(pwd->pw_dir) < 0) {
394 if (login_getcapbool(lc, "requirehome", 0))
395 refused("Home directory not available", "HOMEDIR", 1);
396 if (chdir("/") < 0)
397 refused("Cannot find root directory", "ROOTDIR", 1);
398 if (!quietlog || *pwd->pw_dir)
399 printf("No home directory.\nLogging in with home = \"/\".\n");
400 pwd->pw_dir = strdup("/");
401 if (pwd->pw_dir == NULL) {
402 syslog(LOG_NOTICE, "strdup(): %m");
403 bail(SLEEP_EXIT, 1);
406 seteuid(euid);
407 setegid(egid);
408 if (!quietlog) {
409 quietlog = access(_PATH_HUSHLOGIN, F_OK) == 0;
410 if (!quietlog)
411 pam_silent = 0;
414 shell = login_getcapstr(lc, "shell", pwd->pw_shell, pwd->pw_shell);
415 if (*pwd->pw_shell == '\0')
416 pwd->pw_shell = strdup(_PATH_BSHELL);
417 if (pwd->pw_shell == NULL) {
418 syslog(LOG_NOTICE, "strdup(): %m");
419 bail(SLEEP_EXIT, 1);
421 if (*shell == '\0') /* Not overridden */
422 shell = pwd->pw_shell;
423 if ((shell = strdup(shell)) == NULL) {
424 syslog(LOG_NOTICE, "strdup(): %m");
425 bail(SLEEP_EXIT, 1);
429 * Set device protections, depending on what terminal the
430 * user is logged in. This feature is used on Suns to give
431 * console users better privacy.
433 login_fbtab(tty, pwd->pw_uid, pwd->pw_gid);
436 * Clear flags of the tty. None should be set, and when the
437 * user sets them otherwise, this can cause the chown to fail.
438 * Since it isn't clear that flags are useful on character
439 * devices, we just clear them.
441 * We don't log in the case of EOPNOTSUPP because dev might be
442 * on NFS, which doesn't support chflags.
444 * We don't log in the EROFS because that means that /dev is on
445 * a read only file system and we assume that the permissions there
446 * are sane.
448 if (ttyn != tname && chflags(ttyn, 0))
449 if (errno != EOPNOTSUPP && errno != EROFS)
450 syslog(LOG_ERR, "chflags(%s): %m", ttyn);
451 if (ttyn != tname && chown(ttyn, pwd->pw_uid,
452 (gr = getgrnam(TTYGRPNAME)) ? gr->gr_gid : pwd->pw_gid))
453 if (errno != EROFS)
454 syslog(LOG_ERR, "chown(%s): %m", ttyn);
457 * Exclude cons/vt/ptys only, assume dialup otherwise
458 * TODO: Make dialup tty determination a library call
459 * for consistency (finger etc.)
461 if (hflag && isdialuptty(tty))
462 syslog(LOG_INFO, "DIALUP %s, %s", tty, pwd->pw_name);
464 #ifdef LOGALL
466 * Syslog each successful login, so we don't have to watch
467 * hundreds of wtmp or lastlogin files.
469 if (hflag)
470 syslog(LOG_INFO, "login from %s on %s as %s",
471 hostname, tty, pwd->pw_name);
472 else
473 syslog(LOG_INFO, "login on %s as %s",
474 tty, pwd->pw_name);
475 #endif
478 * If fflag is on, assume caller/authenticator has logged root
479 * login.
481 if (rootlogin && fflag == 0) {
482 if (hflag)
483 syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s FROM %s",
484 username, tty, hostname);
485 else
486 syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s",
487 username, tty);
491 * Destroy environment unless user has requested its
492 * preservation - but preserve TERM in all cases
494 term = getenv("TERM");
495 if (!pflag)
496 environ = envinit;
497 if (term != NULL) {
498 if (setenv("TERM", term, 0) == -1)
499 err(1, "setenv: cannot set TERM=%s", term);
503 * PAM modules might add supplementary groups during pam_setcred().
505 if (setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETGROUP) != 0) {
506 syslog(LOG_ERR, "setusercontext() failed - exiting");
507 bail(NO_SLEEP_EXIT, 1);
510 pam_err = pam_setcred(pamh, pam_silent|PAM_ESTABLISH_CRED);
511 if (pam_err != PAM_SUCCESS) {
512 pam_syslog("pam_setcred()");
513 bail(NO_SLEEP_EXIT, 1);
515 pam_cred_established = 1;
517 pam_err = pam_open_session(pamh, pam_silent);
518 if (pam_err != PAM_SUCCESS) {
519 pam_syslog("pam_open_session()");
520 bail(NO_SLEEP_EXIT, 1);
522 pam_session_established = 1;
525 * We must fork() before setuid() because we need to call
526 * pam_close_session() as root.
528 pid = fork();
529 if (pid < 0) {
530 err(1, "fork");
531 } else if (pid != 0) {
533 * Parent: wait for child to finish, then clean up
534 * session.
536 int status;
537 setproctitle("-%s [pam]", getprogname());
538 waitpid(pid, &status, 0);
539 bail(NO_SLEEP_EXIT, 0);
543 * NOTICE: We are now in the child process!
547 * Add any environment variables the PAM modules may have set.
549 export_pam_environment();
552 * We're done with PAM now; our parent will deal with the rest.
554 pam_end(pamh, 0);
555 pamh = NULL;
558 * We don't need to be root anymore, so set the login name and
559 * the UID.
561 if (setlogin(username) != 0) {
562 syslog(LOG_ERR, "setlogin(%s): %m - exiting", username);
563 bail(NO_SLEEP_EXIT, 1);
565 if (setusercontext(lc, pwd, pwd->pw_uid,
566 LOGIN_SETALL & ~(LOGIN_SETLOGIN|LOGIN_SETGROUP)) != 0) {
567 syslog(LOG_ERR, "setusercontext() failed - exiting");
568 exit(1);
571 if (setenv("SHELL", pwd->pw_shell, 1) == -1)
572 err(1, "setenv: cannot set SHELL=%s", pwd->pw_shell);
573 if (setenv("HOME", pwd->pw_dir, 1) == -1)
574 err(1, "setenv: cannot set HOME=%s", pwd->pw_dir);
575 /* Overwrite "term" from login.conf(5) for any known TERM */
576 if (term == NULL && (tp = stypeof(tty)) != NULL) {
577 if (setenv("TERM", tp, 1) == -1)
578 err(1, "setenv: cannot set TERM=%s", tp);
579 } else {
580 if (setenv("TERM", TERM_UNKNOWN, 0) == -1)
581 err(1, "setenv: cannot set TERM=%s", TERM_UNKNOWN);
584 if (setenv("LOGNAME", username, 1) == -1)
585 err(1, "setenv: cannot set LOGNAME=%s", username);
586 if (setenv("USER", username, 1) == -1)
587 err(1, "setenv: cannot set USER=%s", username);
588 if (setenv("PATH",
589 rootlogin ? _PATH_STDPATH : _PATH_DEFPATH, 0) == -1) {
590 err(1, "setenv: cannot set PATH=%s",
591 rootlogin ? _PATH_STDPATH : _PATH_DEFPATH);
594 if (!quietlog) {
595 const char *cw;
597 cw = login_getcapstr(lc, "copyright", NULL, NULL);
598 if (cw == NULL || motd(cw) == -1)
599 printf("%s", copyright);
601 printf("\n");
603 cw = login_getcapstr(lc, "welcome", NULL, NULL);
604 if (cw != NULL && access(cw, F_OK) == 0)
605 motd(cw);
606 else
607 motd(_PATH_MOTDFILE);
609 if (login_getcapbool(lc_user, "nocheckmail", 0) == 0 &&
610 login_getcapbool(lc, "nocheckmail", 0) == 0) {
611 char *cx;
613 /* $MAIL may have been set by class. */
614 cx = getenv("MAIL");
615 if (cx == NULL) {
616 asprintf(&cx, "%s/%s",
617 _PATH_MAILDIR, pwd->pw_name);
619 if (cx && stat(cx, &st) == 0 && st.st_size != 0)
620 printf("You have %smail.\n",
621 (st.st_mtime > st.st_atime) ? "new " : "");
622 if (getenv("MAIL") == NULL)
623 free(cx);
627 login_close(lc_user);
628 login_close(lc);
630 signal(SIGALRM, SIG_DFL);
631 signal(SIGQUIT, SIG_DFL);
632 signal(SIGINT, SIG_DFL);
633 signal(SIGTSTP, SIG_IGN);
636 * Login shells have a leading '-' in front of argv[0]
638 p = strrchr(pwd->pw_shell, '/');
639 if (asprintf(&arg0, "-%s", p ? p + 1 : pwd->pw_shell) >= MAXPATHLEN) {
640 syslog(LOG_ERR, "user: %s: shell exceeds maximum pathname size",
641 username);
642 errx(1, "shell exceeds maximum pathname size");
643 } else if (arg0 == NULL) {
644 err(1, "asprintf()");
647 execlp(shell, arg0, NULL);
648 err(1, "%s", shell);
651 * That's it, folks!
656 * Attempt to authenticate the user using PAM. Returns 0 if the user is
657 * authenticated, or 1 if not authenticated. If some sort of PAM system
658 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
659 * function returns -1. This can be used as an indication that we should
660 * fall back to a different authentication mechanism.
662 static int
663 auth_pam(void)
665 const char *tmpl_user;
666 const void *item;
667 int rval;
669 pam_err = pam_authenticate(pamh, pam_silent);
670 switch (pam_err) {
672 case PAM_SUCCESS:
674 * With PAM we support the concept of a "template"
675 * user. The user enters a login name which is
676 * authenticated by PAM, usually via a remote service
677 * such as RADIUS or TACACS+. If authentication
678 * succeeds, a different but related "template" name
679 * is used for setting the credentials, shell, and
680 * home directory. The name the user enters need only
681 * exist on the remote authentication server, but the
682 * template name must be present in the local password
683 * database.
685 * This is supported by two various mechanisms in the
686 * individual modules. However, from the application's
687 * point of view, the template user is always passed
688 * back as a changed value of the PAM_USER item.
690 pam_err = pam_get_item(pamh, PAM_USER, &item);
691 if (pam_err == PAM_SUCCESS) {
692 tmpl_user = (const char *)item;
693 if (strcmp(username, tmpl_user) != 0)
694 pwd = getpwnam(tmpl_user);
695 } else {
696 pam_syslog("pam_get_item(PAM_USER)");
698 rval = 0;
699 break;
701 case PAM_AUTH_ERR:
702 case PAM_USER_UNKNOWN:
703 case PAM_MAXTRIES:
704 rval = 1;
705 break;
707 default:
708 pam_syslog("pam_authenticate()");
709 rval = -1;
710 break;
713 if (rval == 0) {
714 pam_err = pam_acct_mgmt(pamh, pam_silent);
715 switch (pam_err) {
716 case PAM_SUCCESS:
717 break;
718 case PAM_NEW_AUTHTOK_REQD:
719 pam_err = pam_chauthtok(pamh,
720 pam_silent|PAM_CHANGE_EXPIRED_AUTHTOK);
721 if (pam_err != PAM_SUCCESS) {
722 pam_syslog("pam_chauthtok()");
723 rval = 1;
725 break;
726 default:
727 pam_syslog("pam_acct_mgmt()");
728 rval = 1;
729 break;
733 if (rval != 0) {
734 pam_end(pamh, pam_err);
735 pamh = NULL;
737 return (rval);
741 * Export any environment variables PAM modules may have set
743 static void
744 export_pam_environment(void)
746 char **pam_env;
747 char **pp;
749 pam_env = pam_getenvlist(pamh);
750 if (pam_env != NULL) {
751 for (pp = pam_env; *pp != NULL; pp++) {
752 export(*pp);
753 free(*pp);
759 * Perform sanity checks on an environment variable:
760 * - Make sure there is an '=' in the string.
761 * - Make sure the string doesn't run on too long.
762 * - Do not export certain variables. This list was taken from the
763 * Solaris pam_putenv(3) man page.
764 * Then export it.
766 static int
767 export(const char *s)
769 static const char *noexport[] = {
770 "SHELL", "HOME", "LOGNAME", "MAIL", "CDPATH",
771 "IFS", "PATH", NULL
773 char *p;
774 const char **pp;
775 size_t n;
777 if (strlen(s) > 1024 || (p = strchr(s, '=')) == NULL)
778 return (0);
779 if (strncmp(s, "LD_", 3) == 0)
780 return (0);
781 for (pp = noexport; *pp != NULL; pp++) {
782 n = strlen(*pp);
783 if (s[n] == '=' && strncmp(s, *pp, n) == 0)
784 return (0);
786 *p = '\0';
787 if (setenv(s, p + 1, 1) == -1)
788 err(1, "setenv: cannot set %s=%s", s, p + 1);
789 *p = '=';
790 return (1);
793 static void
794 usage(void)
797 fprintf(stderr, "usage: login [-fp] [-h hostname] [username]\n");
798 exit(1);
802 * Prompt user and read login name from stdin.
804 static char *
805 getloginname(void)
807 char *nbuf, *p;
808 int ch;
810 nbuf = malloc(MAXLOGNAME);
811 if (nbuf == NULL)
812 err(1, "malloc()");
813 do {
814 printf("%s", prompt);
815 for (p = nbuf; (ch = getchar()) != '\n'; ) {
816 if (ch == EOF) {
817 badlogin(username);
818 bail(NO_SLEEP_EXIT, 0);
820 if (p < nbuf + MAXLOGNAME - 1)
821 *p++ = ch;
823 } while (p == nbuf);
825 *p = '\0';
826 if (nbuf[0] == '-') {
827 pam_silent = 0;
828 memmove(nbuf, nbuf + 1, strlen(nbuf));
829 } else {
830 pam_silent = PAM_SILENT;
832 return nbuf;
836 * SIGINT handler for motd().
838 static volatile int motdinterrupt;
839 static void
840 sigint(int signo __unused)
842 motdinterrupt = 1;
846 * Display the contents of a file (such as /etc/motd).
848 static int
849 motd(const char *motdfile)
851 sig_t oldint;
852 FILE *f;
853 int ch;
855 if ((f = fopen(motdfile, "r")) == NULL)
856 return (-1);
857 motdinterrupt = 0;
858 oldint = signal(SIGINT, sigint);
859 while ((ch = fgetc(f)) != EOF && !motdinterrupt)
860 putchar(ch);
861 signal(SIGINT, oldint);
862 if (ch != EOF || ferror(f)) {
863 fclose(f);
864 return (-1);
866 fclose(f);
867 return (0);
871 * SIGALRM handler, to enforce login prompt timeout.
873 * XXX This can potentially confuse the hell out of PAM. We should
874 * XXX instead implement a conversation function that returns
875 * XXX PAM_CONV_ERR when interrupted by a signal, and have the signal
876 * XXX handler just set a flag.
878 static void
879 timedout(int signo __unused)
882 longjmp(timeout_buf, signo);
885 static void
886 badlogin(char *name)
889 if (failures == 0)
890 return;
891 if (hflag) {
892 syslog(LOG_NOTICE, "%d LOGIN FAILURE%s FROM %s",
893 failures, failures > 1 ? "S" : "", hostname);
894 syslog(LOG_AUTHPRIV|LOG_NOTICE,
895 "%d LOGIN FAILURE%s FROM %s, %s",
896 failures, failures > 1 ? "S" : "", hostname, name);
897 } else {
898 syslog(LOG_NOTICE, "%d LOGIN FAILURE%s ON %s",
899 failures, failures > 1 ? "S" : "", tty);
900 syslog(LOG_AUTHPRIV|LOG_NOTICE,
901 "%d LOGIN FAILURE%s ON %s, %s",
902 failures, failures > 1 ? "S" : "", tty, name);
904 failures = 0;
907 const char *
908 stypeof(char *ttyid)
910 struct ttyent *t;
912 if (ttyid != NULL && *ttyid != '\0') {
913 t = getttynam(ttyid);
914 if (t != NULL && t->ty_type != NULL)
915 return (t->ty_type);
917 return (NULL);
920 static void
921 refused(const char *msg, const char *rtype, int lout)
924 if (msg != NULL)
925 printf("%s.\n", msg);
926 if (hflag)
927 syslog(LOG_NOTICE, "LOGIN %s REFUSED (%s) FROM %s ON TTY %s",
928 pwd->pw_name, rtype, hostname, tty);
929 else
930 syslog(LOG_NOTICE, "LOGIN %s REFUSED (%s) ON TTY %s",
931 pwd->pw_name, rtype, tty);
932 if (lout)
933 bail(SLEEP_EXIT, 1);
937 * Log a PAM error
939 static void
940 pam_syslog(const char *msg)
942 syslog(LOG_ERR, "%s: %s", msg, pam_strerror(pamh, pam_err));
946 * Shut down PAM
948 static void
949 pam_cleanup(void)
952 if (pamh != NULL) {
953 if (pam_session_established) {
954 pam_err = pam_close_session(pamh, 0);
955 if (pam_err != PAM_SUCCESS)
956 pam_syslog("pam_close_session()");
958 pam_session_established = 0;
959 if (pam_cred_established) {
960 pam_err = pam_setcred(pamh, pam_silent|PAM_DELETE_CRED);
961 if (pam_err != PAM_SUCCESS)
962 pam_syslog("pam_setcred()");
964 pam_cred_established = 0;
965 pam_end(pamh, pam_err);
966 pamh = NULL;
971 * Exit, optionally after sleeping a few seconds
973 void
974 bail(int sec, int eval)
977 pam_cleanup();
978 #ifdef USE_BSM_AUDIT
979 if (pwd != NULL)
980 audit_logout();
981 #endif
982 sleep(sec);
983 exit(eval);