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.
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
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 * 4. 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
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 $
38 * $DragonFly: src/usr.bin/login/login.c,v 1.6 2006/01/12 13:43:11 corecode Exp $
43 * login -h hostname (for telnetd, etc.)
44 * login -f name (for pre-authenticated login: datakit, xterm, etc.)
47 #include <sys/copyright.h>
48 #include <sys/param.h>
52 #include <sys/resource.h>
59 #include <login_cap.h>
70 #include <security/pam_appl.h>
71 #include <security/openpam.h>
74 #include "pathnames.h"
76 static int auth_pam(void);
77 static void bail(int, int);
78 static int export(const char *);
79 static void export_pam_environment(void);
80 static int motd(const char *);
81 static void badlogin(char *);
82 static char *getloginname(void);
83 static void pam_syslog(const char *);
84 static void pam_cleanup(void);
85 static void refused(const char *, const char *, int);
86 static const char *stypeof(char *);
87 static void sigint(int);
88 static void timedout(int);
89 static void usage(void);
91 #define TTYGRPNAME "tty" /* group to own ttys */
92 #define DEFAULT_BACKOFF 3
93 #define DEFAULT_RETRIES 10
94 #define DEFAULT_PROMPT "login: "
95 #define DEFAULT_PASSWD_PROMPT "Password:"
96 #define TERM_UNKNOWN "su"
97 #define DEFAULT_WARN (2L * 7L * 86400L) /* Two weeks */
98 #define NO_SLEEP_EXIT 0
102 * This bounds the time given to login. Not a define so it can
103 * be patched on machines where it's too small.
105 static u_int timeout = 300;
107 /* Buffer for signal handling of timeout */
108 static jmp_buf timeout_buf;
113 static char *envinit[1]; /* empty environment list */
116 * Command line flags and arguments
118 static int fflag; /* -f: do not perform authentication */
119 static int hflag; /* -h: login from remote host */
120 static char *hostname; /* hostname from command line */
121 static int pflag; /* -p: preserve environment */
126 static char *username; /* user name */
127 static char *olduser; /* previous user name */
132 static char default_prompt[] = DEFAULT_PROMPT;
133 static const char *prompt;
134 static char default_passwd_prompt[] = DEFAULT_PASSWD_PROMPT;
135 static const char *passwd_prompt;
142 static pam_handle_t *pamh = NULL;
143 static struct pam_conv pamc = { openpam_ttyconv, NULL };
145 static int pam_silent = PAM_SILENT;
146 static int pam_cred_established;
147 static int pam_session_established;
150 main(int argc, char **argv)
154 int retries, backoff;
155 int ask, ch, cnt, quietlog, rootlogin, rval;
160 char tname[sizeof(_PATH_TTY) + 10];
163 const char *shell = NULL;
164 login_cap_t *lc = NULL;
165 login_cap_t *lc_user = NULL;
168 char auditsuccess = 1;
171 signal(SIGQUIT, SIG_IGN);
172 signal(SIGINT, SIG_IGN);
173 signal(SIGHUP, SIG_IGN);
174 if (setjmp(timeout_buf)) {
177 fprintf(stderr, "Login timed out after %d seconds\n",
179 bail(NO_SLEEP_EXIT, 0);
181 signal(SIGALRM, timedout);
183 setpriority(PRIO_PROCESS, 0, 0);
185 openlog("login", LOG_ODELAY, LOG_AUTH);
191 while ((ch = getopt(argc, argv, "fh:p")) != -1)
198 errx(1, "-h option: %s", strerror(EPERM));
199 if (strlen(optarg) >= MAXHOSTNAMELEN)
200 errx(1, "-h option: %s: exceeds maximum "
201 "hostname size", optarg);
211 syslog(LOG_ERR, "invalid flag %c", ch);
218 username = strdup(*argv);
219 if (username == NULL)
226 setproctitle("-%s", getprogname());
228 for (cnt = getdtablesize(); cnt > 2; cnt--)
234 ttyn = ttyname(STDIN_FILENO);
235 if (ttyn == NULL || *ttyn == '\0') {
236 snprintf(tname, sizeof(tname), "%s??", _PATH_TTY);
239 if (strncmp(ttyn, _PATH_DEV, sizeof(_PATH_DEV) -1) == 0)
240 tty = ttyn + sizeof(_PATH_DEV) -1;
245 * Get "login-retries" & "login-backoff" from default class
247 lc = login_getclass(NULL);
248 prompt = login_getcapstr(lc, "login_prompt",
249 default_prompt, default_prompt);
250 passwd_prompt = login_getcapstr(lc, "passwd_prompt",
251 default_passwd_prompt, default_passwd_prompt);
252 retries = login_getcapnum(lc, "login-retries",
253 DEFAULT_RETRIES, DEFAULT_RETRIES);
254 backoff = login_getcapnum(lc, "login-backoff",
255 DEFAULT_BACKOFF, DEFAULT_BACKOFF);
260 * Try to authenticate the user until we succeed or time out.
262 for (cnt = 0;; ask = 1) {
268 username = getloginname();
273 * Note if trying multiple user names; log failures for
274 * previous user name, but don't bother logging one failure
275 * for nonexistent name (mistyped username).
277 if (failures && strcmp(olduser, username) != 0) {
278 if (failures > (pwd ? 0 : 1))
283 * Load the PAM policy and set some variables
285 pam_err = pam_start("login", username, &pamc, &pamh);
286 if (pam_err != PAM_SUCCESS) {
287 pam_syslog("pam_start()");
289 au_login_fail("PAM Error", 1);
291 bail(NO_SLEEP_EXIT, 1);
293 pam_err = pam_set_item(pamh, PAM_TTY, tty);
294 if (pam_err != PAM_SUCCESS) {
295 pam_syslog("pam_set_item(PAM_TTY)");
297 au_login_fail("PAM Error", 1);
299 bail(NO_SLEEP_EXIT, 1);
301 pam_err = pam_set_item(pamh, PAM_RHOST, hostname);
302 if (pam_err != PAM_SUCCESS) {
303 pam_syslog("pam_set_item(PAM_RHOST)");
305 au_login_fail("PAM Error", 1);
307 bail(NO_SLEEP_EXIT, 1);
310 pwd = getpwnam(username);
311 if (pwd != NULL && pwd->pw_uid == 0)
315 * If the -f option was specified and the caller is
316 * root or the caller isn't changing their uid, don't
319 if (pwd != NULL && fflag &&
320 (uid == (uid_t)0 || uid == (uid_t)pwd->pw_uid)) {
321 /* already authenticated */
324 auditsuccess = 0; /* opened a terminal window only */
328 setpriority(PRIO_PROCESS, 0, -4);
330 setpriority(PRIO_PROCESS, 0, 0);
333 if (pwd && rval == 0)
339 * We are not exiting here, but this corresponds to a failed
340 * login event, so set exitstatus to 1.
343 au_login_fail("Login incorrect", 1);
346 printf("Login incorrect\n");
352 * Allow up to 'retry' (10) attempts, but start
353 * backing off after 'backoff' (3) attempts.
355 if (++cnt > backoff) {
356 if (cnt >= retries) {
360 sleep((u_int)((cnt - backoff) * 5));
364 /* committed to login -- turn off timeout */
366 signal(SIGHUP, SIG_DFL);
371 /* Audit successful login. */
377 * Establish the login class.
379 lc = login_getpwclass(pwd);
380 lc_user = login_getuserclass(pwd);
382 if (!(quietlog = login_getcapbool(lc_user, "hushlogin", 0)))
383 quietlog = login_getcapbool(lc, "hushlogin", 0);
386 * Switching needed for NFS with root access disabled.
388 * XXX: This change fails to modify the additional groups for the
389 * process, and as such, may restrict rights normally granted
390 * through those groups.
392 setegid(pwd->pw_gid);
393 seteuid(rootlogin ? 0 : pwd->pw_uid);
394 if (!*pwd->pw_dir || chdir(pwd->pw_dir) < 0) {
395 if (login_getcapbool(lc, "requirehome", 0))
396 refused("Home directory not available", "HOMEDIR", 1);
398 refused("Cannot find root directory", "ROOTDIR", 1);
399 if (!quietlog || *pwd->pw_dir)
400 printf("No home directory.\nLogging in with home = \"/\".\n");
401 pwd->pw_dir = strdup("/");
402 if (pwd->pw_dir == NULL) {
403 syslog(LOG_NOTICE, "strdup(): %m");
410 quietlog = access(_PATH_HUSHLOGIN, F_OK) == 0;
415 shell = login_getcapstr(lc, "shell", pwd->pw_shell, pwd->pw_shell);
416 if (*pwd->pw_shell == '\0')
417 pwd->pw_shell = strdup(_PATH_BSHELL);
418 if (pwd->pw_shell == NULL) {
419 syslog(LOG_NOTICE, "strdup(): %m");
422 if (*shell == '\0') /* Not overridden */
423 shell = pwd->pw_shell;
424 if ((shell = strdup(shell)) == NULL) {
425 syslog(LOG_NOTICE, "strdup(): %m");
430 * Set device protections, depending on what terminal the
431 * user is logged in. This feature is used on Suns to give
432 * console users better privacy.
434 login_fbtab(tty, pwd->pw_uid, pwd->pw_gid);
437 * Clear flags of the tty. None should be set, and when the
438 * user sets them otherwise, this can cause the chown to fail.
439 * Since it isn't clear that flags are useful on character
440 * devices, we just clear them.
442 * We don't log in the case of EOPNOTSUPP because dev might be
443 * on NFS, which doesn't support chflags.
445 * We don't log in the EROFS because that means that /dev is on
446 * a read only file system and we assume that the permissions there
449 if (ttyn != tname && chflags(ttyn, 0))
450 if (errno != EOPNOTSUPP && errno != EROFS)
451 syslog(LOG_ERR, "chflags(%s): %m", ttyn);
452 if (ttyn != tname && chown(ttyn, pwd->pw_uid,
453 (gr = getgrnam(TTYGRPNAME)) ? gr->gr_gid : pwd->pw_gid))
455 syslog(LOG_ERR, "chown(%s): %m", ttyn);
458 * Exclude cons/vt/ptys only, assume dialup otherwise
459 * TODO: Make dialup tty determination a library call
460 * for consistency (finger etc.)
462 if (hflag && isdialuptty(tty))
463 syslog(LOG_INFO, "DIALUP %s, %s", tty, pwd->pw_name);
467 * Syslog each successful login, so we don't have to watch
468 * hundreds of wtmp or lastlogin files.
471 syslog(LOG_INFO, "login from %s on %s as %s",
472 hostname, tty, pwd->pw_name);
474 syslog(LOG_INFO, "login on %s as %s",
479 * If fflag is on, assume caller/authenticator has logged root
482 if (rootlogin && fflag == 0) {
484 syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s FROM %s",
485 username, tty, hostname);
487 syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s",
492 * Destroy environment unless user has requested its
493 * preservation - but preserve TERM in all cases
495 term = getenv("TERM");
499 if (setenv("TERM", term, 0) == -1)
500 err(1, "setenv: cannot set TERM=%s", term);
504 * PAM modules might add supplementary groups during pam_setcred().
506 if (setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETGROUP) != 0) {
507 syslog(LOG_ERR, "setusercontext() failed - exiting");
508 bail(NO_SLEEP_EXIT, 1);
511 pam_err = pam_setcred(pamh, pam_silent|PAM_ESTABLISH_CRED);
512 if (pam_err != PAM_SUCCESS) {
513 pam_syslog("pam_setcred()");
514 bail(NO_SLEEP_EXIT, 1);
516 pam_cred_established = 1;
518 pam_err = pam_open_session(pamh, pam_silent);
519 if (pam_err != PAM_SUCCESS) {
520 pam_syslog("pam_open_session()");
521 bail(NO_SLEEP_EXIT, 1);
523 pam_session_established = 1;
526 * We must fork() before setuid() because we need to call
527 * pam_close_session() as root.
532 } else if (pid != 0) {
534 * Parent: wait for child to finish, then clean up
538 setproctitle("-%s [pam]", getprogname());
539 waitpid(pid, &status, 0);
540 bail(NO_SLEEP_EXIT, 0);
544 * NOTICE: We are now in the child process!
548 * Add any environment variables the PAM modules may have set.
550 export_pam_environment();
553 * We're done with PAM now; our parent will deal with the rest.
559 * We don't need to be root anymore, so set the login name and
562 if (setlogin(username) != 0) {
563 syslog(LOG_ERR, "setlogin(%s): %m - exiting", username);
564 bail(NO_SLEEP_EXIT, 1);
566 if (setusercontext(lc, pwd, pwd->pw_uid,
567 LOGIN_SETALL & ~(LOGIN_SETLOGIN|LOGIN_SETGROUP)) != 0) {
568 syslog(LOG_ERR, "setusercontext() failed - exiting");
572 if (setenv("SHELL", pwd->pw_shell, 1) == -1)
573 err(1, "setenv: cannot set SHELL=%s", pwd->pw_shell);
574 if (setenv("HOME", pwd->pw_dir, 1) == -1)
575 err(1, "setenv: cannot set HOME=%s", pwd->pw_dir);
576 /* Overwrite "term" from login.conf(5) for any known TERM */
577 if (term == NULL && (tp = stypeof(tty)) != NULL) {
578 if (setenv("TERM", tp, 1) == -1)
579 err(1, "setenv: cannot set TERM=%s", tp);
581 if (setenv("TERM", TERM_UNKNOWN, 0) == -1)
582 err(1, "setenv: cannot set TERM=%s", TERM_UNKNOWN);
585 if (setenv("LOGNAME", username, 1) == -1)
586 err(1, "setenv: cannot set LOGNAME=%s", username);
587 if (setenv("USER", username, 1) == -1)
588 err(1, "setenv: cannot set USER=%s", username);
590 rootlogin ? _PATH_STDPATH : _PATH_DEFPATH, 0) == -1) {
591 err(1, "setenv: cannot set PATH=%s",
592 rootlogin ? _PATH_STDPATH : _PATH_DEFPATH);
598 cw = login_getcapstr(lc, "copyright", NULL, NULL);
599 if (cw == NULL || motd(cw) == -1)
600 printf("%s", copyright);
604 cw = login_getcapstr(lc, "welcome", NULL, NULL);
605 if (cw != NULL && access(cw, F_OK) == 0)
608 motd(_PATH_MOTDFILE);
610 if (login_getcapbool(lc_user, "nocheckmail", 0) == 0 &&
611 login_getcapbool(lc, "nocheckmail", 0) == 0) {
614 /* $MAIL may have been set by class. */
617 asprintf(&cx, "%s/%s",
618 _PATH_MAILDIR, pwd->pw_name);
620 if (cx && stat(cx, &st) == 0 && st.st_size != 0)
621 printf("You have %smail.\n",
622 (st.st_mtime > st.st_atime) ? "new " : "");
623 if (getenv("MAIL") == NULL)
628 login_close(lc_user);
631 signal(SIGALRM, SIG_DFL);
632 signal(SIGQUIT, SIG_DFL);
633 signal(SIGINT, SIG_DFL);
634 signal(SIGTSTP, SIG_IGN);
637 * Login shells have a leading '-' in front of argv[0]
639 p = strrchr(pwd->pw_shell, '/');
640 if (asprintf(&arg0, "-%s", p ? p + 1 : pwd->pw_shell) >= MAXPATHLEN) {
641 syslog(LOG_ERR, "user: %s: shell exceeds maximum pathname size",
643 errx(1, "shell exceeds maximum pathname size");
644 } else if (arg0 == NULL) {
645 err(1, "asprintf()");
648 execlp(shell, arg0, NULL);
657 * Attempt to authenticate the user using PAM. Returns 0 if the user is
658 * authenticated, or 1 if not authenticated. If some sort of PAM system
659 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
660 * function returns -1. This can be used as an indication that we should
661 * fall back to a different authentication mechanism.
666 const char *tmpl_user;
670 pam_err = pam_authenticate(pamh, pam_silent);
675 * With PAM we support the concept of a "template"
676 * user. The user enters a login name which is
677 * authenticated by PAM, usually via a remote service
678 * such as RADIUS or TACACS+. If authentication
679 * succeeds, a different but related "template" name
680 * is used for setting the credentials, shell, and
681 * home directory. The name the user enters need only
682 * exist on the remote authentication server, but the
683 * template name must be present in the local password
686 * This is supported by two various mechanisms in the
687 * individual modules. However, from the application's
688 * point of view, the template user is always passed
689 * back as a changed value of the PAM_USER item.
691 pam_err = pam_get_item(pamh, PAM_USER, &item);
692 if (pam_err == PAM_SUCCESS) {
693 tmpl_user = (const char *)item;
694 if (strcmp(username, tmpl_user) != 0)
695 pwd = getpwnam(tmpl_user);
697 pam_syslog("pam_get_item(PAM_USER)");
703 case PAM_USER_UNKNOWN:
709 pam_syslog("pam_authenticate()");
715 pam_err = pam_acct_mgmt(pamh, pam_silent);
719 case PAM_NEW_AUTHTOK_REQD:
720 pam_err = pam_chauthtok(pamh,
721 pam_silent|PAM_CHANGE_EXPIRED_AUTHTOK);
722 if (pam_err != PAM_SUCCESS) {
723 pam_syslog("pam_chauthtok()");
728 pam_syslog("pam_acct_mgmt()");
735 pam_end(pamh, pam_err);
742 * Export any environment variables PAM modules may have set
745 export_pam_environment(void)
750 pam_env = pam_getenvlist(pamh);
751 if (pam_env != NULL) {
752 for (pp = pam_env; *pp != NULL; pp++) {
760 * Perform sanity checks on an environment variable:
761 * - Make sure there is an '=' in the string.
762 * - Make sure the string doesn't run on too long.
763 * - Do not export certain variables. This list was taken from the
764 * Solaris pam_putenv(3) man page.
768 export(const char *s)
770 static const char *noexport[] = {
771 "SHELL", "HOME", "LOGNAME", "MAIL", "CDPATH",
778 if (strlen(s) > 1024 || (p = strchr(s, '=')) == NULL)
780 if (strncmp(s, "LD_", 3) == 0)
782 for (pp = noexport; *pp != NULL; pp++) {
784 if (s[n] == '=' && strncmp(s, *pp, n) == 0)
788 if (setenv(s, p + 1, 1) == -1)
789 err(1, "setenv: cannot set %s=%s", s, p + 1);
798 fprintf(stderr, "usage: login [-fp] [-h hostname] [username]\n");
803 * Prompt user and read login name from stdin.
811 nbuf = malloc(MAXLOGNAME);
815 printf("%s", prompt);
816 for (p = nbuf; (ch = getchar()) != '\n'; ) {
819 bail(NO_SLEEP_EXIT, 0);
821 if (p < nbuf + MAXLOGNAME - 1)
827 if (nbuf[0] == '-') {
829 memmove(nbuf, nbuf + 1, strlen(nbuf));
831 pam_silent = PAM_SILENT;
837 * SIGINT handler for motd().
839 static volatile int motdinterrupt;
841 sigint(int signo __unused)
847 * Display the contents of a file (such as /etc/motd).
850 motd(const char *motdfile)
856 if ((f = fopen(motdfile, "r")) == NULL)
859 oldint = signal(SIGINT, sigint);
860 while ((ch = fgetc(f)) != EOF && !motdinterrupt)
862 signal(SIGINT, oldint);
863 if (ch != EOF || ferror(f)) {
872 * SIGALRM handler, to enforce login prompt timeout.
874 * XXX This can potentially confuse the hell out of PAM. We should
875 * XXX instead implement a conversation function that returns
876 * XXX PAM_CONV_ERR when interrupted by a signal, and have the signal
877 * XXX handler just set a flag.
880 timedout(int signo __unused)
883 longjmp(timeout_buf, signo);
893 syslog(LOG_NOTICE, "%d LOGIN FAILURE%s FROM %s",
894 failures, failures > 1 ? "S" : "", hostname);
895 syslog(LOG_AUTHPRIV|LOG_NOTICE,
896 "%d LOGIN FAILURE%s FROM %s, %s",
897 failures, failures > 1 ? "S" : "", hostname, name);
899 syslog(LOG_NOTICE, "%d LOGIN FAILURE%s ON %s",
900 failures, failures > 1 ? "S" : "", tty);
901 syslog(LOG_AUTHPRIV|LOG_NOTICE,
902 "%d LOGIN FAILURE%s ON %s, %s",
903 failures, failures > 1 ? "S" : "", tty, name);
913 if (ttyid != NULL && *ttyid != '\0') {
914 t = getttynam(ttyid);
915 if (t != NULL && t->ty_type != NULL)
922 refused(const char *msg, const char *rtype, int lout)
926 printf("%s.\n", msg);
928 syslog(LOG_NOTICE, "LOGIN %s REFUSED (%s) FROM %s ON TTY %s",
929 pwd->pw_name, rtype, hostname, tty);
931 syslog(LOG_NOTICE, "LOGIN %s REFUSED (%s) ON TTY %s",
932 pwd->pw_name, rtype, tty);
941 pam_syslog(const char *msg)
943 syslog(LOG_ERR, "%s: %s", msg, pam_strerror(pamh, pam_err));
954 if (pam_session_established) {
955 pam_err = pam_close_session(pamh, 0);
956 if (pam_err != PAM_SUCCESS)
957 pam_syslog("pam_close_session()");
959 pam_session_established = 0;
960 if (pam_cred_established) {
961 pam_err = pam_setcred(pamh, pam_silent|PAM_DELETE_CRED);
962 if (pam_err != PAM_SUCCESS)
963 pam_syslog("pam_setcred()");
965 pam_cred_established = 0;
966 pam_end(pamh, pam_err);
972 * Exit, optionally after sleeping a few seconds
975 bail(int sec, int eval)