1 /* vi: set sw=4 ts=4: */
3 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
6 //config: bool "login (24 kb)"
8 //config: select FEATURE_SYSLOG
10 //config: login is used when signing onto a system.
12 //config: Note that busybox binary must be setuid root for this applet to
13 //config: work properly.
15 //config:config LOGIN_SESSION_AS_CHILD
16 //config: bool "Run logged in session in a child process"
17 //config: default y if PAM
18 //config: depends on LOGIN
20 //config: Run the logged in session in a child process. This allows
21 //config: login to clean up things such as utmp entries or PAM sessions
22 //config: when the login session is complete. If you use PAM, you
23 //config: almost always would want this to be set to Y, else PAM session
24 //config: will not be cleaned up.
26 //config:config LOGIN_SCRIPTS
27 //config: bool "Support login scripts"
28 //config: depends on LOGIN
31 //config: Enable this if you want login to execute $LOGIN_PRE_SUID_SCRIPT
32 //config: just prior to switching from root to logged-in user.
34 //config:config FEATURE_NOLOGIN
35 //config: bool "Support /etc/nologin"
37 //config: depends on LOGIN
39 //config: The file /etc/nologin is used by (some versions of) login(1).
40 //config: If it exists, non-root logins are prohibited.
42 //config:config FEATURE_SECURETTY
43 //config: bool "Support /etc/securetty"
45 //config: depends on LOGIN
47 //config: The file /etc/securetty is used by (some versions of) login(1).
48 //config: The file contains the device names of tty lines (one per line,
49 //config: without leading /dev/) on which root is allowed to login.
51 //applet:/* Needs to be run by root or be suid root - needs to change uid and gid: */
52 //applet:IF_LOGIN(APPLET(login, BB_DIR_BIN, BB_SUID_REQUIRE))
54 //kbuild:lib-$(CONFIG_LOGIN) += login.o
56 //usage:#define login_trivial_usage
57 //usage: "[-p] [-h HOST] [[-f] USER]"
58 //usage:#define login_full_usage "\n\n"
59 //usage: "Begin a new session on the system\n"
60 //usage: "\n -f Don't authenticate (user already authenticated)"
61 //usage: "\n -h HOST Host user came from (for network logins)"
62 //usage: "\n -p Preserve environment"
65 #include "common_bufsiz.h"
69 # include <selinux/selinux.h> /* for is_selinux_enabled() */
70 # include <selinux/get_context_list.h> /* for get_default_context() */
71 # /* from deprecated <selinux/flask.h>: */
72 # undef SECCLASS_CHR_FILE
73 # define SECCLASS_CHR_FILE 10
77 /* PAM may include <locale.h>. We may need to undefine bbox's stub define: */
79 /* For some obscure reason, PAM is not in pam/xxx, but in security/xxx.
80 * Apparently they like to confuse people. */
81 # include <security/pam_appl.h>
82 # include <security/pam_misc.h>
85 /* This supposedly can be used to avoid double password prompt,
86 * if used instead of standard misc_conv():
88 * "When we want to authenticate first with local method and then with tacacs for example,
89 * the password is asked for local method and if not good is asked a second time for tacacs.
90 * So if we want to authenticate a user with tacacs, and the user exists localy, the password is
91 * asked two times before authentication is accepted."
93 * However, code looks shaky. For example, why misc_conv() return value is ignored?
94 * Are msg[i] and resp[i] indexes handled correctly?
96 static char *passwd = NULL;
97 static int my_conv(int num_msg, const struct pam_message **msg,
98 struct pam_response **resp, void *data)
101 for (i = 0; i < num_msg; i++) {
102 switch (msg[i]->msg_style) {
103 case PAM_PROMPT_ECHO_OFF:
104 if (passwd == NULL) {
105 misc_conv(num_msg, msg, resp, data);
106 passwd = xstrdup(resp[i]->resp);
110 resp[0] = xzalloc(sizeof(struct pam_response));
111 resp[0]->resp = passwd;
113 resp[0]->resp_retcode = PAM_SUCCESS;
126 static const struct pam_conv conv = {
134 EMPTY_USERNAME_COUNT = 10,
135 /* Some users found 32 chars limit to be too low: */
141 struct termios tty_attrs;
143 #define G (*(struct globals*)bb_common_bufsiz1)
144 #define INIT_G() do { setup_common_bufsiz(); } while (0)
147 #if ENABLE_FEATURE_NOLOGIN
148 static void die_if_nologin(void)
154 fp = fopen_for_read("/etc/nologin");
155 if (!fp) /* assuming it does not exist */
158 while ((c = getc(fp)) != EOF) {
165 puts("\r\nSystem closed for routine maintenance\r");
169 /* Users say that they do need this prior to exit: */
170 tcdrain(STDOUT_FILENO);
174 # define die_if_nologin() ((void)0)
178 static void initselinux(char *username, char *full_tty,
179 security_context_t *user_sid)
181 security_context_t old_tty_sid, new_tty_sid;
183 if (!is_selinux_enabled())
186 if (get_default_context(username, NULL, user_sid)) {
187 bb_error_msg_and_die("can't get SID for %s", username);
189 if (getfilecon(full_tty, &old_tty_sid) < 0) {
190 bb_perror_msg_and_die("getfilecon(%s) failed", full_tty);
192 if (security_compute_relabel(*user_sid, old_tty_sid,
193 SECCLASS_CHR_FILE, &new_tty_sid) != 0) {
194 bb_perror_msg_and_die("security_change_sid(%s) failed", full_tty);
196 if (setfilecon(full_tty, new_tty_sid) != 0) {
197 bb_perror_msg_and_die("chsid(%s, %s) failed", full_tty, new_tty_sid);
202 #if ENABLE_LOGIN_SCRIPTS
203 static void run_login_script(struct passwd *pw, char *full_tty)
207 t_argv[0] = getenv("LOGIN_PRE_SUID_SCRIPT");
210 xsetenv("LOGIN_TTY", full_tty);
211 xsetenv("LOGIN_USER", pw->pw_name);
212 xsetenv("LOGIN_UID", utoa(pw->pw_uid));
213 xsetenv("LOGIN_GID", utoa(pw->pw_gid));
214 xsetenv("LOGIN_SHELL", pw->pw_shell);
215 spawn_and_wait(t_argv); /* NOMMU-friendly */
216 unsetenv("LOGIN_TTY");
217 unsetenv("LOGIN_USER");
218 unsetenv("LOGIN_UID");
219 unsetenv("LOGIN_GID");
220 unsetenv("LOGIN_SHELL");
224 void run_login_script(struct passwd *pw, char *full_tty);
227 #if ENABLE_LOGIN_SESSION_AS_CHILD && ENABLE_PAM
228 static void login_pam_end(pam_handle_t *pamh)
232 pamret = pam_setcred(pamh, PAM_DELETE_CRED);
233 if (pamret != PAM_SUCCESS) {
234 bb_error_msg("pam_%s failed: %s (%d)", "setcred",
235 pam_strerror(pamh, pamret), pamret);
237 pamret = pam_close_session(pamh, 0);
238 if (pamret != PAM_SUCCESS) {
239 bb_error_msg("pam_%s failed: %s (%d)", "close_session",
240 pam_strerror(pamh, pamret), pamret);
242 pamret = pam_end(pamh, pamret);
243 if (pamret != PAM_SUCCESS) {
244 bb_error_msg("pam_%s failed: %s (%d)", "end",
245 pam_strerror(pamh, pamret), pamret);
248 #endif /* ENABLE_PAM */
250 static void get_username_or_die(char *buf, int size_buf)
254 cntdown = EMPTY_USERNAME_COUNT;
256 print_login_prompt();
257 /* skip whitespace */
267 } while (isspace(c)); /* maybe isblank? */
270 if (!fgets(buf, size_buf-2, stdin))
272 if (!strchr(buf, '\n'))
274 while ((unsigned char)*buf > ' ')
279 static void motd(void)
283 fd = open(bb_path_motd_file, O_RDONLY);
286 bb_copyfd_eof(fd, STDOUT_FILENO);
291 static void alarm_handler(int sig UNUSED_PARAM)
293 /* This is the escape hatch! Poor serial line users and the like
294 * arrive here when their connection is broken.
295 * We don't want to block here */
296 ndelay_on(STDOUT_FILENO);
297 /* Test for correct attr restoring:
298 * run "getty 0 -" from a shell, enter bogus username, stop at
299 * password prompt, let it time out. Without the tcsetattr below,
300 * when you are back at shell prompt, echo will be still off.
302 tcsetattr_stdin_TCSANOW(&G.tty_attrs);
303 printf("\r\nLogin timed out after %u seconds\r\n", TIMEOUT);
305 /* unix API is brain damaged regarding O_NONBLOCK,
306 * we should undo it, or else we can affect other processes */
307 ndelay_off(STDOUT_FILENO);
311 int login_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
312 int login_main(int argc UNUSED_PARAM, char **argv)
315 LOGIN_OPT_f = (1<<0),
316 LOGIN_OPT_h = (1<<1),
317 LOGIN_OPT_p = (1<<2),
320 char username[USERNAME_SIZE];
325 char *opt_host = NULL;
326 char *opt_user = opt_user; /* for compiler */
329 IF_SELINUX(security_context_t user_sid = NULL;)
334 const char *failed_msg;
335 struct passwd pwdstruct;
339 #if ENABLE_LOGIN_SESSION_AS_CHILD
345 /* More of suid paranoia if called by non-root: */
346 /* Clear dangerous stuff, set PATH */
347 run_by_root = !sanitize_env_if_suid();
349 /* Mandatory paranoia for suid applet:
350 * ensure that fd# 0,1,2 are opened (at least to /dev/null)
351 * and any extra open fd's are closed.
353 bb_daemon_helper(DAEMON_CLOSE_EXTRA_FDS);
356 opt = getopt32(argv, "f:h:p", &opt_user, &opt_host);
357 if (opt & LOGIN_OPT_f) {
359 bb_error_msg_and_die("-f is for root only");
360 safe_strncpy(username, opt_user, sizeof(username));
363 if (argv[0]) /* user from command line (getty) */
364 safe_strncpy(username, argv[0], sizeof(username));
366 /* Save tty attributes - and by doing it, check that it's indeed a tty */
367 if (tcgetattr(STDIN_FILENO, &G.tty_attrs) < 0
368 || !isatty(STDOUT_FILENO)
369 /*|| !isatty(STDERR_FILENO) - no, guess some people might want to redirect this */
371 return EXIT_FAILURE; /* Must be a terminal */
374 /* We install timeout handler only _after_ we saved G.tty_attrs */
375 signal(SIGALRM, alarm_handler);
378 /* Find out and memorize our tty name */
379 full_tty = xmalloc_ttyname(STDIN_FILENO);
381 full_tty = xstrdup("UNKNOWN");
382 short_tty = skip_dev_pfx(full_tty);
385 fromhost = xasprintf(" on '%s' from '%s'", short_tty, opt_host);
387 fromhost = xasprintf(" on '%s'", short_tty);
390 /* Was breaking "login <username>" from shell command line: */
393 openlog(applet_name, LOG_PID | LOG_CONS, LOG_AUTH);
396 /* flush away any type-ahead (as getty does) */
397 tcflush(0, TCIFLUSH);
400 get_username_or_die(username, sizeof(username));
403 pamret = pam_start("login", username, &conv, &pamh);
404 if (pamret != PAM_SUCCESS) {
405 failed_msg = "start";
406 goto pam_auth_failed;
408 /* set TTY (so things like securetty work) */
409 pamret = pam_set_item(pamh, PAM_TTY, short_tty);
410 if (pamret != PAM_SUCCESS) {
411 failed_msg = "set_item(TTY)";
412 goto pam_auth_failed;
416 pamret = pam_set_item(pamh, PAM_RHOST, opt_host);
417 if (pamret != PAM_SUCCESS) {
418 failed_msg = "set_item(RHOST)";
419 goto pam_auth_failed;
422 if (!(opt & LOGIN_OPT_f)) {
423 pamret = pam_authenticate(pamh, 0);
424 if (pamret != PAM_SUCCESS) {
425 failed_msg = "authenticate";
426 goto pam_auth_failed;
427 /* TODO: or just "goto auth_failed"
428 * since user seems to enter wrong password
429 * (in this case pamret == 7)
433 /* check that the account is healthy */
434 pamret = pam_acct_mgmt(pamh, 0);
435 if (pamret != PAM_SUCCESS) {
436 failed_msg = "acct_mgmt";
437 goto pam_auth_failed;
441 /* gcc: "dereferencing type-punned pointer breaks aliasing rules..."
442 * thus we cast to (void*) */
443 if (pam_get_item(pamh, PAM_USER, (void*)&pamuser) != PAM_SUCCESS) {
444 failed_msg = "get_item(USER)";
445 goto pam_auth_failed;
447 if (!pamuser || !pamuser[0])
449 safe_strncpy(username, pamuser, sizeof(username));
450 /* Don't use "pw = getpwnam(username);",
451 * PAM is said to be capable of destroying static storage
452 * used by getpwnam(). We are using safe(r) function */
454 getpwnam_r(username, &pwdstruct, pwdbuf, sizeof(pwdbuf), &pw);
457 pamret = pam_open_session(pamh, 0);
458 if (pamret != PAM_SUCCESS) {
459 failed_msg = "open_session";
460 goto pam_auth_failed;
462 pamret = pam_setcred(pamh, PAM_ESTABLISH_CRED);
463 if (pamret != PAM_SUCCESS) {
464 failed_msg = "setcred";
465 goto pam_auth_failed;
467 break; /* success, continue login process */
470 /* syslog, because we don't want potential attacker
471 * to know _why_ login failed */
472 syslog(LOG_WARNING, "pam_%s call failed: %s (%d)", failed_msg,
473 pam_strerror(pamh, pamret), pamret);
474 safe_strncpy(username, "UNKNOWN", sizeof(username));
476 pw = getpwnam(username);
478 strcpy(username, "UNKNOWN");
482 if (pw->pw_passwd[0] == '!' || pw->pw_passwd[0] == '*')
485 if (opt & LOGIN_OPT_f)
486 break; /* -f USER: success without asking passwd */
488 if (pw->pw_uid == 0 && !is_tty_secure(short_tty))
491 /* Don't check the password if password entry is empty (!) */
492 if (!pw->pw_passwd[0])
495 /* Password reading and authorization takes place here.
496 * Note that reads (in no-echo mode) trash tty attributes.
497 * If we get interrupted by SIGALRM, we need to restore attrs.
499 if (ask_and_check_password(pw) > 0)
501 #endif /* ENABLE_PAM */
504 bb_do_delay(LOGIN_FAIL_DELAY);
505 /* TODO: doesn't sound like correct English phrase to me */
506 puts("Login incorrect");
508 syslog(LOG_WARNING, "invalid password for '%s'%s",
511 if (ENABLE_FEATURE_CLEAN_UP)
520 /* We can ignore /etc/nologin if we are logging in as root,
521 * it doesn't matter whether we are run by root or not */
525 #if ENABLE_LOGIN_SESSION_AS_CHILD
527 if (child_pid != 0) {
529 bb_perror_msg("vfork");
531 if (safe_waitpid(child_pid, NULL, 0) == -1)
532 bb_perror_msg("waitpid");
533 update_utmp_DEAD_PROCESS(child_pid);
535 IF_PAM(login_pam_end(pamh);)
540 IF_SELINUX(initselinux(username, full_tty, &user_sid);)
542 /* Try these, but don't complain if they fail.
543 * _f_chown is safe wrt race t=ttyname(0);...;chown(t); */
544 fchown(0, pw->pw_uid, pw->pw_gid);
547 update_utmp(getpid(), USER_PROCESS, short_tty, username, run_by_root ? opt_host : NULL);
549 /* We trust environment only if we run by root */
550 if (ENABLE_LOGIN_SCRIPTS && run_by_root)
551 run_login_script(pw, full_tty);
554 setup_environment(pw->pw_shell,
555 (!(opt & LOGIN_OPT_p) * SETUP_ENV_CLEARENV) + SETUP_ENV_CHANGEENV,
559 /* Modules such as pam_env will setup the PAM environment,
560 * which should be copied into the new environment. */
561 pamenv = pam_getenvlist(pamh);
562 if (pamenv) while (*pamenv) {
568 if (access(".hushlogin", F_OK) != 0)
572 syslog(LOG_INFO, "root login%s", fromhost);
574 if (ENABLE_FEATURE_CLEAN_UP)
577 /* well, a simple setexeccon() here would do the job as well,
578 * but let's play the game for now */
579 IF_SELINUX(set_current_security_context(user_sid);)
581 // util-linux login also does:
582 // /* start new session */
584 // /* TIOCSCTTY: steal tty from other process group */
585 // if (ioctl(0, TIOCSCTTY, 1)) error_msg...
586 // BBox login used to do this (see above):
588 // If this stuff is really needed, add it and explain why!
590 /* Set signals to defaults */
591 /* Non-ignored signals revert to SIG_DFL on exec anyway */
592 /*signal(SIGALRM, SIG_DFL);*/
594 /* Is this correct? This way user can ctrl-c out of /etc/profile,
595 * potentially creating security breach (tested with bash 3.0).
596 * But without this, bash 3.0 will not enable ctrl-c either.
597 * Maybe bash is buggy?
598 * Need to find out what standards say about /bin/login -
599 * should we leave SIGINT etc enabled or disabled? */
600 signal(SIGINT, SIG_DFL);
602 /* Exec login shell with no additional parameters */
603 run_shell(pw->pw_shell, 1, NULL);
605 /* return EXIT_FAILURE; - not reached */