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 * 3. All advertising materials mentioning features or use of this software
21 * must display the following acknowledgement:
22 * This product includes software developed by the University of
23 * California, Berkeley and its contributors.
24 * 4. Neither the name of the University nor the names of its contributors
25 * may be used to endorse or promote products derived from this software
26 * without specific prior written permission.
28 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40 * @(#)login.c 8.4 (Berkeley) 4/2/94
41 * $FreeBSD: src/usr.bin/login/login.c,v 1.106 2007/07/04 00:00:40 scf Exp $
42 * $DragonFly: src/usr.bin/login/login.c,v 1.6 2006/01/12 13:43:11 corecode Exp $
47 * login -h hostname (for telnetd, etc.)
48 * login -f name (for pre-authenticated login: datakit, xterm, etc.)
51 #include <sys/copyright.h>
52 #include <sys/param.h>
56 #include <sys/resource.h>
63 #include <login_cap.h>
74 #include <security/pam_appl.h>
75 #include <security/openpam.h>
78 #include "pathnames.h"
80 static int auth_pam(void);
81 static void bail(int, int);
82 static int export(const char *);
83 static void export_pam_environment(void);
84 static int motd(const char *);
85 static void badlogin(char *);
86 static char *getloginname(void);
87 static void pam_syslog(const char *);
88 static void pam_cleanup(void);
89 static void refused(const char *, const char *, int);
90 static const char *stypeof(char *);
91 static void sigint(int);
92 static void timedout(int);
93 static void usage(void);
95 #define TTYGRPNAME "tty" /* group to own ttys */
96 #define DEFAULT_BACKOFF 3
97 #define DEFAULT_RETRIES 10
98 #define DEFAULT_PROMPT "login: "
99 #define DEFAULT_PASSWD_PROMPT "Password:"
100 #define TERM_UNKNOWN "su"
101 #define DEFAULT_WARN (2L * 7L * 86400L) /* Two weeks */
102 #define NO_SLEEP_EXIT 0
106 * This bounds the time given to login. Not a define so it can
107 * be patched on machines where it's too small.
109 static u_int timeout = 300;
111 /* Buffer for signal handling of timeout */
112 static jmp_buf timeout_buf;
117 static char *envinit[1]; /* empty environment list */
120 * Command line flags and arguments
122 static int fflag; /* -f: do not perform authentication */
123 static int hflag; /* -h: login from remote host */
124 static char *hostname; /* hostname from command line */
125 static int pflag; /* -p: preserve environment */
130 static char *username; /* user name */
131 static char *olduser; /* previous user name */
136 static char default_prompt[] = DEFAULT_PROMPT;
137 static const char *prompt;
138 static char default_passwd_prompt[] = DEFAULT_PASSWD_PROMPT;
139 static const char *passwd_prompt;
146 static pam_handle_t *pamh = NULL;
147 static struct pam_conv pamc = { openpam_ttyconv, NULL };
149 static int pam_silent = PAM_SILENT;
150 static int pam_cred_established;
151 static int pam_session_established;
154 main(int argc, char **argv)
158 int retries, backoff;
159 int ask, ch, cnt, quietlog, rootlogin, rval;
164 char tname[sizeof(_PATH_TTY) + 10];
167 const char *shell = NULL;
168 login_cap_t *lc = NULL;
169 login_cap_t *lc_user = NULL;
172 char auditsuccess = 1;
175 signal(SIGQUIT, SIG_IGN);
176 signal(SIGINT, SIG_IGN);
177 signal(SIGHUP, SIG_IGN);
178 if (setjmp(timeout_buf)) {
181 fprintf(stderr, "Login timed out after %d seconds\n",
183 bail(NO_SLEEP_EXIT, 0);
185 signal(SIGALRM, timedout);
187 setpriority(PRIO_PROCESS, 0, 0);
189 openlog("login", LOG_ODELAY, LOG_AUTH);
195 while ((ch = getopt(argc, argv, "fh:p")) != -1)
202 errx(1, "-h option: %s", strerror(EPERM));
203 if (strlen(optarg) >= MAXHOSTNAMELEN)
204 errx(1, "-h option: %s: exceeds maximum "
205 "hostname size", optarg);
215 syslog(LOG_ERR, "invalid flag %c", ch);
222 username = strdup(*argv);
223 if (username == NULL)
230 setproctitle("-%s", getprogname());
232 for (cnt = getdtablesize(); cnt > 2; cnt--)
238 ttyn = ttyname(STDIN_FILENO);
239 if (ttyn == NULL || *ttyn == '\0') {
240 snprintf(tname, sizeof(tname), "%s??", _PATH_TTY);
243 if (strncmp(ttyn, _PATH_DEV, sizeof(_PATH_DEV) -1) == 0)
244 tty = ttyn + sizeof(_PATH_DEV) -1;
249 * Get "login-retries" & "login-backoff" from default class
251 lc = login_getclass(NULL);
252 prompt = login_getcapstr(lc, "login_prompt",
253 default_prompt, default_prompt);
254 passwd_prompt = login_getcapstr(lc, "passwd_prompt",
255 default_passwd_prompt, default_passwd_prompt);
256 retries = login_getcapnum(lc, "login-retries",
257 DEFAULT_RETRIES, DEFAULT_RETRIES);
258 backoff = login_getcapnum(lc, "login-backoff",
259 DEFAULT_BACKOFF, DEFAULT_BACKOFF);
264 * Try to authenticate the user until we succeed or time out.
266 for (cnt = 0;; ask = 1) {
272 username = getloginname();
277 * Note if trying multiple user names; log failures for
278 * previous user name, but don't bother logging one failure
279 * for nonexistent name (mistyped username).
281 if (failures && strcmp(olduser, username) != 0) {
282 if (failures > (pwd ? 0 : 1))
287 * Load the PAM policy and set some variables
289 pam_err = pam_start("login", username, &pamc, &pamh);
290 if (pam_err != PAM_SUCCESS) {
291 pam_syslog("pam_start()");
293 au_login_fail("PAM Error", 1);
295 bail(NO_SLEEP_EXIT, 1);
297 pam_err = pam_set_item(pamh, PAM_TTY, tty);
298 if (pam_err != PAM_SUCCESS) {
299 pam_syslog("pam_set_item(PAM_TTY)");
301 au_login_fail("PAM Error", 1);
303 bail(NO_SLEEP_EXIT, 1);
305 pam_err = pam_set_item(pamh, PAM_RHOST, hostname);
306 if (pam_err != PAM_SUCCESS) {
307 pam_syslog("pam_set_item(PAM_RHOST)");
309 au_login_fail("PAM Error", 1);
311 bail(NO_SLEEP_EXIT, 1);
314 pwd = getpwnam(username);
315 if (pwd != NULL && pwd->pw_uid == 0)
319 * If the -f option was specified and the caller is
320 * root or the caller isn't changing their uid, don't
323 if (pwd != NULL && fflag &&
324 (uid == (uid_t)0 || uid == (uid_t)pwd->pw_uid)) {
325 /* already authenticated */
328 auditsuccess = 0; /* opened a terminal window only */
332 setpriority(PRIO_PROCESS, 0, -4);
334 setpriority(PRIO_PROCESS, 0, 0);
337 if (pwd && rval == 0)
343 * We are not exiting here, but this corresponds to a failed
344 * login event, so set exitstatus to 1.
347 au_login_fail("Login incorrect", 1);
350 printf("Login incorrect\n");
356 * Allow up to 'retry' (10) attempts, but start
357 * backing off after 'backoff' (3) attempts.
359 if (++cnt > backoff) {
360 if (cnt >= retries) {
364 sleep((u_int)((cnt - backoff) * 5));
368 /* committed to login -- turn off timeout */
370 signal(SIGHUP, SIG_DFL);
375 /* Audit successful login. */
381 * Establish the login class.
383 lc = login_getpwclass(pwd);
384 lc_user = login_getuserclass(pwd);
386 if (!(quietlog = login_getcapbool(lc_user, "hushlogin", 0)))
387 quietlog = login_getcapbool(lc, "hushlogin", 0);
390 * Switching needed for NFS with root access disabled.
392 * XXX: This change fails to modify the additional groups for the
393 * process, and as such, may restrict rights normally granted
394 * through those groups.
396 setegid(pwd->pw_gid);
397 seteuid(rootlogin ? 0 : pwd->pw_uid);
398 if (!*pwd->pw_dir || chdir(pwd->pw_dir) < 0) {
399 if (login_getcapbool(lc, "requirehome", 0))
400 refused("Home directory not available", "HOMEDIR", 1);
402 refused("Cannot find root directory", "ROOTDIR", 1);
403 if (!quietlog || *pwd->pw_dir)
404 printf("No home directory.\nLogging in with home = \"/\".\n");
405 pwd->pw_dir = strdup("/");
406 if (pwd->pw_dir == NULL) {
407 syslog(LOG_NOTICE, "strdup(): %m");
414 quietlog = access(_PATH_HUSHLOGIN, F_OK) == 0;
419 shell = login_getcapstr(lc, "shell", pwd->pw_shell, pwd->pw_shell);
420 if (*pwd->pw_shell == '\0')
421 pwd->pw_shell = strdup(_PATH_BSHELL);
422 if (pwd->pw_shell == NULL) {
423 syslog(LOG_NOTICE, "strdup(): %m");
426 if (*shell == '\0') /* Not overridden */
427 shell = pwd->pw_shell;
428 if ((shell = strdup(shell)) == NULL) {
429 syslog(LOG_NOTICE, "strdup(): %m");
434 * Set device protections, depending on what terminal the
435 * user is logged in. This feature is used on Suns to give
436 * console users better privacy.
438 login_fbtab(tty, pwd->pw_uid, pwd->pw_gid);
441 * Clear flags of the tty. None should be set, and when the
442 * user sets them otherwise, this can cause the chown to fail.
443 * Since it isn't clear that flags are useful on character
444 * devices, we just clear them.
446 * We don't log in the case of EOPNOTSUPP because dev might be
447 * on NFS, which doesn't support chflags.
449 * We don't log in the EROFS because that means that /dev is on
450 * a read only file system and we assume that the permissions there
453 if (ttyn != tname && chflags(ttyn, 0))
454 if (errno != EOPNOTSUPP && errno != EROFS)
455 syslog(LOG_ERR, "chflags(%s): %m", ttyn);
456 if (ttyn != tname && chown(ttyn, pwd->pw_uid,
457 (gr = getgrnam(TTYGRPNAME)) ? gr->gr_gid : pwd->pw_gid))
459 syslog(LOG_ERR, "chown(%s): %m", ttyn);
462 * Exclude cons/vt/ptys only, assume dialup otherwise
463 * TODO: Make dialup tty determination a library call
464 * for consistency (finger etc.)
466 if (hflag && isdialuptty(tty))
467 syslog(LOG_INFO, "DIALUP %s, %s", tty, pwd->pw_name);
471 * Syslog each successful login, so we don't have to watch
472 * hundreds of wtmp or lastlogin files.
475 syslog(LOG_INFO, "login from %s on %s as %s",
476 hostname, tty, pwd->pw_name);
478 syslog(LOG_INFO, "login on %s as %s",
483 * If fflag is on, assume caller/authenticator has logged root
486 if (rootlogin && fflag == 0) {
488 syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s FROM %s",
489 username, tty, hostname);
491 syslog(LOG_NOTICE, "ROOT LOGIN (%s) ON %s",
496 * Destroy environment unless user has requested its
497 * preservation - but preserve TERM in all cases
499 term = getenv("TERM");
503 if (setenv("TERM", term, 0) == -1)
504 err(1, "setenv: cannot set TERM=%s", term);
508 * PAM modules might add supplementary groups during pam_setcred().
510 if (setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETGROUP) != 0) {
511 syslog(LOG_ERR, "setusercontext() failed - exiting");
512 bail(NO_SLEEP_EXIT, 1);
515 pam_err = pam_setcred(pamh, pam_silent|PAM_ESTABLISH_CRED);
516 if (pam_err != PAM_SUCCESS) {
517 pam_syslog("pam_setcred()");
518 bail(NO_SLEEP_EXIT, 1);
520 pam_cred_established = 1;
522 pam_err = pam_open_session(pamh, pam_silent);
523 if (pam_err != PAM_SUCCESS) {
524 pam_syslog("pam_open_session()");
525 bail(NO_SLEEP_EXIT, 1);
527 pam_session_established = 1;
530 * We must fork() before setuid() because we need to call
531 * pam_close_session() as root.
536 } else if (pid != 0) {
538 * Parent: wait for child to finish, then clean up
542 setproctitle("-%s [pam]", getprogname());
543 waitpid(pid, &status, 0);
544 bail(NO_SLEEP_EXIT, 0);
548 * NOTICE: We are now in the child process!
552 * Add any environment variables the PAM modules may have set.
554 export_pam_environment();
557 * We're done with PAM now; our parent will deal with the rest.
563 * We don't need to be root anymore, so set the login name and
566 if (setlogin(username) != 0) {
567 syslog(LOG_ERR, "setlogin(%s): %m - exiting", username);
568 bail(NO_SLEEP_EXIT, 1);
570 if (setusercontext(lc, pwd, pwd->pw_uid,
571 LOGIN_SETALL & ~(LOGIN_SETLOGIN|LOGIN_SETGROUP)) != 0) {
572 syslog(LOG_ERR, "setusercontext() failed - exiting");
576 if (setenv("SHELL", pwd->pw_shell, 1) == -1)
577 err(1, "setenv: cannot set SHELL=%s", pwd->pw_shell);
578 if (setenv("HOME", pwd->pw_dir, 1) == -1)
579 err(1, "setenv: cannot set HOME=%s", pwd->pw_dir);
580 /* Overwrite "term" from login.conf(5) for any known TERM */
581 if (term == NULL && (tp = stypeof(tty)) != NULL) {
582 if (setenv("TERM", tp, 1) == -1)
583 err(1, "setenv: cannot set TERM=%s", tp);
585 if (setenv("TERM", TERM_UNKNOWN, 0) == -1)
586 err(1, "setenv: cannot set TERM=%s", TERM_UNKNOWN);
589 if (setenv("LOGNAME", username, 1) == -1)
590 err(1, "setenv: cannot set LOGNAME=%s", username);
591 if (setenv("USER", username, 1) == -1)
592 err(1, "setenv: cannot set USER=%s", username);
594 rootlogin ? _PATH_STDPATH : _PATH_DEFPATH, 0) == -1) {
595 err(1, "setenv: cannot set PATH=%s",
596 rootlogin ? _PATH_STDPATH : _PATH_DEFPATH);
602 cw = login_getcapstr(lc, "copyright", NULL, NULL);
603 if (cw == NULL || motd(cw) == -1)
604 printf("%s", copyright);
608 cw = login_getcapstr(lc, "welcome", NULL, NULL);
609 if (cw != NULL && access(cw, F_OK) == 0)
612 motd(_PATH_MOTDFILE);
614 if (login_getcapbool(lc_user, "nocheckmail", 0) == 0 &&
615 login_getcapbool(lc, "nocheckmail", 0) == 0) {
618 /* $MAIL may have been set by class. */
621 asprintf(&cx, "%s/%s",
622 _PATH_MAILDIR, pwd->pw_name);
624 if (cx && stat(cx, &st) == 0 && st.st_size != 0)
625 printf("You have %smail.\n",
626 (st.st_mtime > st.st_atime) ? "new " : "");
627 if (getenv("MAIL") == NULL)
632 login_close(lc_user);
635 signal(SIGALRM, SIG_DFL);
636 signal(SIGQUIT, SIG_DFL);
637 signal(SIGINT, SIG_DFL);
638 signal(SIGTSTP, SIG_IGN);
641 * Login shells have a leading '-' in front of argv[0]
643 p = strrchr(pwd->pw_shell, '/');
644 if (asprintf(&arg0, "-%s", p ? p + 1 : pwd->pw_shell) >= MAXPATHLEN) {
645 syslog(LOG_ERR, "user: %s: shell exceeds maximum pathname size",
647 errx(1, "shell exceeds maximum pathname size");
648 } else if (arg0 == NULL) {
649 err(1, "asprintf()");
652 execlp(shell, arg0, NULL);
661 * Attempt to authenticate the user using PAM. Returns 0 if the user is
662 * authenticated, or 1 if not authenticated. If some sort of PAM system
663 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
664 * function returns -1. This can be used as an indication that we should
665 * fall back to a different authentication mechanism.
670 const char *tmpl_user;
674 pam_err = pam_authenticate(pamh, pam_silent);
679 * With PAM we support the concept of a "template"
680 * user. The user enters a login name which is
681 * authenticated by PAM, usually via a remote service
682 * such as RADIUS or TACACS+. If authentication
683 * succeeds, a different but related "template" name
684 * is used for setting the credentials, shell, and
685 * home directory. The name the user enters need only
686 * exist on the remote authentication server, but the
687 * template name must be present in the local password
690 * This is supported by two various mechanisms in the
691 * individual modules. However, from the application's
692 * point of view, the template user is always passed
693 * back as a changed value of the PAM_USER item.
695 pam_err = pam_get_item(pamh, PAM_USER, &item);
696 if (pam_err == PAM_SUCCESS) {
697 tmpl_user = (const char *)item;
698 if (strcmp(username, tmpl_user) != 0)
699 pwd = getpwnam(tmpl_user);
701 pam_syslog("pam_get_item(PAM_USER)");
707 case PAM_USER_UNKNOWN:
713 pam_syslog("pam_authenticate()");
719 pam_err = pam_acct_mgmt(pamh, pam_silent);
723 case PAM_NEW_AUTHTOK_REQD:
724 pam_err = pam_chauthtok(pamh,
725 pam_silent|PAM_CHANGE_EXPIRED_AUTHTOK);
726 if (pam_err != PAM_SUCCESS) {
727 pam_syslog("pam_chauthtok()");
732 pam_syslog("pam_acct_mgmt()");
739 pam_end(pamh, pam_err);
746 * Export any environment variables PAM modules may have set
749 export_pam_environment(void)
754 pam_env = pam_getenvlist(pamh);
755 if (pam_env != NULL) {
756 for (pp = pam_env; *pp != NULL; pp++) {
764 * Perform sanity checks on an environment variable:
765 * - Make sure there is an '=' in the string.
766 * - Make sure the string doesn't run on too long.
767 * - Do not export certain variables. This list was taken from the
768 * Solaris pam_putenv(3) man page.
772 export(const char *s)
774 static const char *noexport[] = {
775 "SHELL", "HOME", "LOGNAME", "MAIL", "CDPATH",
782 if (strlen(s) > 1024 || (p = strchr(s, '=')) == NULL)
784 if (strncmp(s, "LD_", 3) == 0)
786 for (pp = noexport; *pp != NULL; pp++) {
788 if (s[n] == '=' && strncmp(s, *pp, n) == 0)
792 if (setenv(s, p + 1, 1) == -1)
793 err(1, "setenv: cannot set %s=%s", s, p + 1);
802 fprintf(stderr, "usage: login [-fp] [-h hostname] [username]\n");
807 * Prompt user and read login name from stdin.
815 nbuf = malloc(MAXLOGNAME);
819 printf("%s", prompt);
820 for (p = nbuf; (ch = getchar()) != '\n'; ) {
823 bail(NO_SLEEP_EXIT, 0);
825 if (p < nbuf + MAXLOGNAME - 1)
831 if (nbuf[0] == '-') {
833 memmove(nbuf, nbuf + 1, strlen(nbuf));
835 pam_silent = PAM_SILENT;
841 * SIGINT handler for motd().
843 static volatile int motdinterrupt;
845 sigint(int signo __unused)
851 * Display the contents of a file (such as /etc/motd).
854 motd(const char *motdfile)
860 if ((f = fopen(motdfile, "r")) == NULL)
863 oldint = signal(SIGINT, sigint);
864 while ((ch = fgetc(f)) != EOF && !motdinterrupt)
866 signal(SIGINT, oldint);
867 if (ch != EOF || ferror(f)) {
876 * SIGALRM handler, to enforce login prompt timeout.
878 * XXX This can potentially confuse the hell out of PAM. We should
879 * XXX instead implement a conversation function that returns
880 * XXX PAM_CONV_ERR when interrupted by a signal, and have the signal
881 * XXX handler just set a flag.
884 timedout(int signo __unused)
887 longjmp(timeout_buf, signo);
897 syslog(LOG_NOTICE, "%d LOGIN FAILURE%s FROM %s",
898 failures, failures > 1 ? "S" : "", hostname);
899 syslog(LOG_AUTHPRIV|LOG_NOTICE,
900 "%d LOGIN FAILURE%s FROM %s, %s",
901 failures, failures > 1 ? "S" : "", hostname, name);
903 syslog(LOG_NOTICE, "%d LOGIN FAILURE%s ON %s",
904 failures, failures > 1 ? "S" : "", tty);
905 syslog(LOG_AUTHPRIV|LOG_NOTICE,
906 "%d LOGIN FAILURE%s ON %s, %s",
907 failures, failures > 1 ? "S" : "", tty, name);
917 if (ttyid != NULL && *ttyid != '\0') {
918 t = getttynam(ttyid);
919 if (t != NULL && t->ty_type != NULL)
926 refused(const char *msg, const char *rtype, int lout)
930 printf("%s.\n", msg);
932 syslog(LOG_NOTICE, "LOGIN %s REFUSED (%s) FROM %s ON TTY %s",
933 pwd->pw_name, rtype, hostname, tty);
935 syslog(LOG_NOTICE, "LOGIN %s REFUSED (%s) ON TTY %s",
936 pwd->pw_name, rtype, tty);
945 pam_syslog(const char *msg)
947 syslog(LOG_ERR, "%s: %s", msg, pam_strerror(pamh, pam_err));
958 if (pam_session_established) {
959 pam_err = pam_close_session(pamh, 0);
960 if (pam_err != PAM_SUCCESS)
961 pam_syslog("pam_close_session()");
963 pam_session_established = 0;
964 if (pam_cred_established) {
965 pam_err = pam_setcred(pamh, pam_silent|PAM_DELETE_CRED);
966 if (pam_err != PAM_SUCCESS)
967 pam_syslog("pam_setcred()");
969 pam_cred_established = 0;
970 pam_end(pamh, pam_err);
976 * Exit, optionally after sleeping a few seconds
979 bail(int sec, int eval)