1 /* vi: set sw=4 ts=4: */
3 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
6 //config: bool "login (25 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"
64 //usage: "\n$LOGIN_TIMEOUT Seconds (default 60, 0 - disable)"
65 //usage: IF_LOGIN_SCRIPTS(
66 //usage: "\n$LOGIN_PRE_SUID_SCRIPT Execute before user ID change"
70 #include "common_bufsiz.h"
74 # include <selinux/selinux.h> /* for is_selinux_enabled() */
75 # include <selinux/get_context_list.h> /* for get_default_context() */
76 # /* from deprecated <selinux/flask.h>: */
77 # undef SECCLASS_CHR_FILE
78 # define SECCLASS_CHR_FILE 10
82 /* PAM may include <locale.h>. We may need to undefine bbox's stub define: */
84 /* For some obscure reason, PAM is not in pam/xxx, but in security/xxx.
85 * Apparently they like to confuse people. */
86 # include <security/pam_appl.h>
87 # include <security/pam_misc.h>
90 /* This supposedly can be used to avoid double password prompt,
91 * if used instead of standard misc_conv():
93 * "When we want to authenticate first with local method and then with tacacs for example,
94 * the password is asked for local method and if not good is asked a second time for tacacs.
95 * So if we want to authenticate a user with tacacs, and the user exists localy, the password is
96 * asked two times before authentication is accepted."
98 * However, code looks shaky. For example, why misc_conv() return value is ignored?
99 * Are msg[i] and resp[i] indexes handled correctly?
101 static char *passwd
= NULL
;
102 static int my_conv(int num_msg
, const struct pam_message
**msg
,
103 struct pam_response
**resp
, void *data
)
106 for (i
= 0; i
< num_msg
; i
++) {
107 switch (msg
[i
]->msg_style
) {
108 case PAM_PROMPT_ECHO_OFF
:
109 if (passwd
== NULL
) {
110 misc_conv(num_msg
, msg
, resp
, data
);
111 passwd
= xstrdup(resp
[i
]->resp
);
115 resp
[0] = xzalloc(sizeof(struct pam_response
));
116 resp
[0]->resp
= passwd
;
118 resp
[0]->resp_retcode
= PAM_SUCCESS
;
131 static const struct pam_conv conv
= {
138 EMPTY_USERNAME_COUNT
= 10,
139 /* Some users found 32 chars limit to be too low: */
145 struct termios tty_attrs
;
148 #define G (*(struct globals*)bb_common_bufsiz1)
149 #define INIT_G() do { setup_common_bufsiz(); } while (0)
152 #if ENABLE_FEATURE_NOLOGIN
153 static void die_if_nologin(void)
159 fp
= fopen_for_read("/etc/nologin");
160 if (!fp
) /* assuming it does not exist */
163 while ((c
= getc(fp
)) != EOF
) {
170 puts("\r\nSystem closed for routine maintenance\r");
174 /* Users say that they do need this prior to exit: */
175 tcdrain(STDOUT_FILENO
);
179 # define die_if_nologin() ((void)0)
183 static void initselinux(char *username
, char *full_tty
,
184 security_context_t
*user_sid
)
186 security_context_t old_tty_sid
, new_tty_sid
;
188 if (!is_selinux_enabled())
191 if (get_default_context(username
, NULL
, user_sid
)) {
192 bb_error_msg_and_die("can't get SID for %s", username
);
194 if (getfilecon(full_tty
, &old_tty_sid
) < 0) {
195 bb_perror_msg_and_die("getfilecon(%s) failed", full_tty
);
197 if (security_compute_relabel(*user_sid
, old_tty_sid
,
198 SECCLASS_CHR_FILE
, &new_tty_sid
) != 0) {
199 bb_perror_msg_and_die("security_change_sid(%s) failed", full_tty
);
201 if (setfilecon(full_tty
, new_tty_sid
) != 0) {
202 bb_perror_msg_and_die("chsid(%s, %s) failed", full_tty
, new_tty_sid
);
207 #if ENABLE_LOGIN_SCRIPTS
208 static void run_login_script(struct passwd
*pw
, char *full_tty
)
212 t_argv
[0] = getenv("LOGIN_PRE_SUID_SCRIPT");
215 xsetenv("LOGIN_TTY", full_tty
);
216 xsetenv("LOGIN_USER", pw
->pw_name
);
217 xsetenv("LOGIN_UID", utoa(pw
->pw_uid
));
218 xsetenv("LOGIN_GID", utoa(pw
->pw_gid
));
219 xsetenv("LOGIN_SHELL", pw
->pw_shell
);
220 spawn_and_wait(t_argv
); /* NOMMU-friendly */
221 unsetenv("LOGIN_TTY");
222 unsetenv("LOGIN_USER");
223 unsetenv("LOGIN_UID");
224 unsetenv("LOGIN_GID");
225 unsetenv("LOGIN_SHELL");
229 void run_login_script(struct passwd
*pw
, char *full_tty
);
232 #if ENABLE_LOGIN_SESSION_AS_CHILD && ENABLE_PAM
233 static void login_pam_end(pam_handle_t
*pamh
)
237 pamret
= pam_setcred(pamh
, PAM_DELETE_CRED
);
238 if (pamret
!= PAM_SUCCESS
) {
239 bb_error_msg("pam_%s failed: %s (%d)", "setcred",
240 pam_strerror(pamh
, pamret
), pamret
);
242 pamret
= pam_close_session(pamh
, 0);
243 if (pamret
!= PAM_SUCCESS
) {
244 bb_error_msg("pam_%s failed: %s (%d)", "close_session",
245 pam_strerror(pamh
, pamret
), pamret
);
247 pamret
= pam_end(pamh
, pamret
);
248 if (pamret
!= PAM_SUCCESS
) {
249 bb_error_msg("pam_%s failed: %s (%d)", "end",
250 pam_strerror(pamh
, pamret
), pamret
);
254 # define login_pam_end(pamh) ((void)0)
257 static void get_username_or_die(char *buf
, int size_buf
)
261 cntdown
= EMPTY_USERNAME_COUNT
;
263 print_login_prompt();
264 /* skip whitespace */
274 } while (isspace(c
)); /* maybe isblank? */
277 if (!fgets(buf
, size_buf
-2, stdin
))
279 if (!strchr(buf
, '\n'))
281 while ((unsigned char)*buf
> ' ')
286 static void motd(void)
290 fd
= open(bb_path_motd_file
, O_RDONLY
);
293 bb_copyfd_eof(fd
, STDOUT_FILENO
);
298 static void alarm_handler(int sig UNUSED_PARAM
)
300 /* This is the escape hatch! Poor serial line users and the like
301 * arrive here when their connection is broken.
302 * We don't want to block here */
303 ndelay_on(STDOUT_FILENO
);
304 /* Test for correct attr restoring:
305 * run "getty 0 -" from a shell, enter bogus username, stop at
306 * password prompt, let it time out. Without the tcsetattr below,
307 * when you are back at shell prompt, echo will be still off.
309 tcsetattr_stdin_TCSANOW(&G
.tty_attrs
);
310 printf("\r\nLogin timed out after %u seconds\r\n", G
.timeout
);
312 /* unix API is brain damaged regarding O_NONBLOCK,
313 * we should undo it, or else we can affect other processes */
314 ndelay_off(STDOUT_FILENO
);
318 int login_main(int argc
, char **argv
) MAIN_EXTERNALLY_VISIBLE
;
319 int login_main(int argc UNUSED_PARAM
, char **argv
)
322 LOGIN_OPT_f
= (1<<0),
323 LOGIN_OPT_h
= (1<<1),
324 LOGIN_OPT_p
= (1<<2),
327 char username
[USERNAME_SIZE
];
332 char *opt_host
= NULL
;
333 char *opt_user
= opt_user
; /* for compiler */
336 IF_SELINUX(security_context_t user_sid
= NULL
;)
341 const char *failed_msg
;
342 struct passwd pwdstruct
;
346 #if ENABLE_LOGIN_SESSION_AS_CHILD
349 IF_FEATURE_UTMP(pid_t my_pid
;)
353 G
.timeout
= xatoi_positive(getenv("LOGIN_TIMEOUT") ? : "60");
355 /* More of suid paranoia if called by non-root: */
356 /* Clear dangerous stuff, set PATH */
357 run_by_root
= !sanitize_env_if_suid();
359 /* Mandatory paranoia for suid applet:
360 * ensure that fd# 0,1,2 are opened (at least to /dev/null)
361 * and any extra open fd's are closed.
363 bb_daemon_helper(DAEMON_CLOSE_EXTRA_FDS
);
366 opt
= getopt32(argv
, "f:h:p", &opt_user
, &opt_host
);
367 if (opt
& LOGIN_OPT_f
) {
369 bb_simple_error_msg_and_die("-f is for root only");
370 safe_strncpy(username
, opt_user
, sizeof(username
));
373 if (argv
[0]) /* user from command line (getty) */
374 safe_strncpy(username
, argv
[0], sizeof(username
));
376 /* Save tty attributes - and by doing it, check that it's indeed a tty */
377 if (tcgetattr(STDIN_FILENO
, &G
.tty_attrs
) < 0
378 || !isatty(STDOUT_FILENO
)
379 /*|| !isatty(STDERR_FILENO) - no, guess some people might want to redirect this */
381 return EXIT_FAILURE
; /* Must be a terminal */
384 /* We install timeout handler only _after_ we saved G.tty_attrs */
385 signal(SIGALRM
, alarm_handler
);
388 /* Find out and memorize our tty name */
389 full_tty
= xmalloc_ttyname(STDIN_FILENO
);
391 full_tty
= xstrdup("UNKNOWN");
392 short_tty
= skip_dev_pfx(full_tty
);
395 fromhost
= xasprintf(" on '%s' from '%s'", short_tty
, opt_host
);
397 fromhost
= xasprintf(" on '%s'", short_tty
);
400 /* Was breaking "login <username>" from shell command line: */
403 openlog(applet_name
, LOG_PID
| LOG_CONS
, LOG_AUTH
);
406 /* flush away any type-ahead (as getty does) */
407 tcflush(0, TCIFLUSH
);
410 get_username_or_die(username
, sizeof(username
));
413 pamret
= pam_start("login", username
, &conv
, &pamh
);
414 if (pamret
!= PAM_SUCCESS
) {
415 failed_msg
= "start";
416 goto pam_auth_failed
;
418 /* set TTY (so things like securetty work) */
419 pamret
= pam_set_item(pamh
, PAM_TTY
, short_tty
);
420 if (pamret
!= PAM_SUCCESS
) {
421 failed_msg
= "set_item(TTY)";
422 goto pam_auth_failed
;
426 pamret
= pam_set_item(pamh
, PAM_RHOST
, opt_host
);
427 if (pamret
!= PAM_SUCCESS
) {
428 failed_msg
= "set_item(RHOST)";
429 goto pam_auth_failed
;
432 if (!(opt
& LOGIN_OPT_f
)) {
433 pamret
= pam_authenticate(pamh
, 0);
434 if (pamret
!= PAM_SUCCESS
) {
435 failed_msg
= "authenticate";
436 goto pam_auth_failed
;
437 /* TODO: or just "goto auth_failed"
438 * since user seems to enter wrong password
439 * (in this case pamret == 7)
443 /* check that the account is healthy */
444 pamret
= pam_acct_mgmt(pamh
, 0);
445 if (pamret
== PAM_NEW_AUTHTOK_REQD
) {
446 pamret
= pam_chauthtok(pamh
, PAM_CHANGE_EXPIRED_AUTHTOK
);
448 if (pamret
!= PAM_SUCCESS
) {
449 failed_msg
= "acct_mgmt";
450 goto pam_auth_failed
;
454 /* gcc: "dereferencing type-punned pointer breaks aliasing rules..."
455 * thus we cast to (void*) */
456 if (pam_get_item(pamh
, PAM_USER
, (void*)&pamuser
) != PAM_SUCCESS
) {
457 failed_msg
= "get_item(USER)";
458 goto pam_auth_failed
;
460 if (!pamuser
|| !pamuser
[0])
462 safe_strncpy(username
, pamuser
, sizeof(username
));
463 /* Don't use "pw = getpwnam(username);",
464 * PAM is said to be capable of destroying static storage
465 * used by getpwnam(). We are using safe(r) function */
467 getpwnam_r(username
, &pwdstruct
, pwdbuf
, sizeof(pwdbuf
), &pw
);
470 pamret
= pam_open_session(pamh
, 0);
471 if (pamret
!= PAM_SUCCESS
) {
472 failed_msg
= "open_session";
473 goto pam_auth_failed
;
475 pamret
= pam_setcred(pamh
, PAM_ESTABLISH_CRED
);
476 if (pamret
!= PAM_SUCCESS
) {
477 failed_msg
= "setcred";
478 goto pam_auth_failed
;
480 break; /* success, continue login process */
483 /* syslog, because we don't want potential attacker
484 * to know _why_ login failed */
485 syslog(LOG_WARNING
, "pam_%s call failed: %s (%d)", failed_msg
,
486 pam_strerror(pamh
, pamret
), pamret
);
488 safe_strncpy(username
, "UNKNOWN", sizeof(username
));
490 pw
= getpwnam(username
);
492 strcpy(username
, "UNKNOWN");
496 if (pw
->pw_passwd
[0] == '!' || pw
->pw_passwd
[0] == '*')
499 if (opt
& LOGIN_OPT_f
)
500 break; /* -f USER: success without asking passwd */
502 if (pw
->pw_uid
== 0 && !is_tty_secure(short_tty
))
505 /* Don't check the password if password entry is empty (!) */
506 if (!pw
->pw_passwd
[0])
509 /* Password reading and authorization takes place here.
510 * Note that reads (in no-echo mode) trash tty attributes.
511 * If we get interrupted by SIGALRM, we need to restore attrs.
513 if (ask_and_check_password(pw
) > 0)
515 #endif /* ENABLE_PAM */
518 pause_after_failed_login();
519 /* TODO: doesn't sound like correct English phrase to me */
520 puts("Login incorrect");
521 syslog(LOG_WARNING
, "invalid password for '%s'%s",
524 if (ENABLE_FEATURE_CLEAN_UP
)
532 /* We can ignore /etc/nologin if we are logging in as root,
533 * it doesn't matter whether we are run by root or not */
537 IF_FEATURE_UTMP(my_pid
= getpid();)
538 update_utmp(my_pid
, USER_PROCESS
, short_tty
, username
, run_by_root
? opt_host
: NULL
);
540 #if ENABLE_LOGIN_SESSION_AS_CHILD
542 if (child_pid
!= 0) {
544 bb_simple_perror_msg("vfork");
546 wait_for_exitstatus(child_pid
);
548 update_utmp_DEAD_PROCESS(my_pid
);
554 IF_SELINUX(initselinux(username
, full_tty
, &user_sid
);)
556 /* Try these, but don't complain if they fail.
557 * _f_chown is safe wrt race t=ttyname(0);...;chown(t); */
558 fchown(0, pw
->pw_uid
, pw
->pw_gid
);
561 /* We trust environment only if we run by root */
562 if (ENABLE_LOGIN_SCRIPTS
&& run_by_root
)
563 run_login_script(pw
, full_tty
);
566 setup_environment(pw
->pw_shell
,
567 (!(opt
& LOGIN_OPT_p
) * SETUP_ENV_CLEARENV
)
568 + SETUP_ENV_CHANGEENV
573 /* Modules such as pam_env will setup the PAM environment,
574 * which should be copied into the new environment. */
575 pamenv
= pam_getenvlist(pamh
);
576 if (pamenv
) while (*pamenv
) {
582 if (access(".hushlogin", F_OK
) != 0)
586 syslog(LOG_INFO
, "root login%s", fromhost
);
588 if (ENABLE_FEATURE_CLEAN_UP
)
591 /* well, a simple setexeccon() here would do the job as well,
592 * but let's play the game for now */
593 IF_SELINUX(set_current_security_context(user_sid
);)
595 // util-linux login also does:
596 // /* start new session */
598 // /* TIOCSCTTY: steal tty from other process group */
599 // if (ioctl(0, TIOCSCTTY, 1)) error_msg...
600 // BBox login used to do this (see above):
602 // If this stuff is really needed, add it and explain why!
604 /* Set signals to defaults */
605 /* Non-ignored signals revert to SIG_DFL on exec anyway */
606 /*signal(SIGALRM, SIG_DFL);*/
608 /* Is this correct? This way user can ctrl-c out of /etc/profile,
609 * potentially creating security breach (tested with bash 3.0).
610 * But without this, bash 3.0 will not enable ctrl-c either.
611 * Maybe bash is buggy?
612 * Need to find out what standards say about /bin/login -
613 * should we leave SIGINT etc enabled or disabled?
614 * Also note: sulogin does not do it! Why?
616 signal(SIGINT
, SIG_DFL
);
618 /* Exec login shell with no additional parameters */
619 exec_login_shell(pw
->pw_shell
);
621 /* return EXIT_FAILURE; - not reached */